use std::collections::{HashMap, HashSet};
use std::fmt;
use super::critic::{self, Piece, Token};
use super::diff::{continues, diff_markdown, marker_len, open_paragraph, table_row};
use super::redline::{RedlineOptions, Source, redline};
use super::write::named;
use super::{MarkdownError, MarkdownOptions, docx_to_markdown, docx_to_markdown_stories};
use crate::document_comparer::{accept_revisions, reject_revisions};
use crate::inspect;
pub const DEFAULT_COLUMNS: usize = 72;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Attribution {
pub author: String,
pub date: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PatchOptions {
pub old_name: String,
pub new_name: String,
pub owner: Attribution,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Locator {
Line(usize),
Paragraph {
story: String,
index: usize,
},
}
impl fmt::Display for Locator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Line(line) => write!(f, "line:{line}"),
Self::Paragraph { story, index } => {
f.write_str(&crate::ids::paragraph_id(story, *index))
}
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Comment {
pub author: String,
pub date: String,
pub text: String,
pub on: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Change {
pub old: String,
pub new: String,
pub author: String,
pub date: String,
pub comment: Option<Comment>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Hunk {
pub at: Locator,
pub removed: bool,
pub text: String,
pub changes: Vec<Change>,
pub comments: Vec<Comment>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Patch {
pub old_name: String,
pub new_name: String,
pub owner: Attribution,
pub hunks: Vec<Hunk>,
}
impl Patch {
pub fn render(&self, columns: usize) -> String {
if self.hunks.is_empty() {
return String::new();
}
let mut out = format!(
"--- a/{}\n+++ b/{}\t{}\t{}\n",
path_name(&self.old_name),
path_name(&self.new_name),
self.owner.author,
self.owner.date
);
for (index, hunk) in self.hunks.iter().enumerate() {
if index > 0 {
out.push('\n');
}
let sign = if hunk.removed { "-" } else { "" };
out.push_str(&format!("@@ {sign}[{}] @@\n", hunk.at));
out.push_str(&wrap(&hunk.text, columns));
out.push('\n');
}
out
}
}
impl fmt::Display for Patch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.render(DEFAULT_COLUMNS))
}
}
fn path_name(name: &str) -> &str {
let name = name.strip_prefix("./").unwrap_or(name);
name.trim_start_matches('/')
}
pub fn patch_markdown(old: &str, new: &str, options: &PatchOptions) -> Patch {
let (mut patch, texts) = build(&diff_markdown(old, new), options);
let lines = |text: &str| -> Vec<String> {
text.replace("\r\n", "\n")
.lines()
.map(str::to_string)
.collect()
};
let (old_lines, new_lines) = (lines(old), lines(new));
let (mut old_from, mut new_from) = (0, 0);
let texts = texts.into_iter().filter(|t| t.hunk.is_some());
for (
hunk,
Paragraphs {
old: old_text,
new: new_text,
..
},
) in patch.hunks.iter_mut().zip(texts)
{
let (text, lines, from) = if hunk.removed {
(old_text, &old_lines, &mut old_from)
} else {
(new_text, &new_lines, &mut new_from)
};
let first = text.trim_start_matches('\n').lines().next().unwrap_or("");
if first.is_empty() {
continue;
}
if let Some(found) = lines[(*from).min(lines.len())..]
.iter()
.position(|l| l == first)
{
let line = *from + found;
hunk.at = Locator::Line(line + 1);
*from = line + 1;
}
}
patch
}
pub fn patch_critic(critic: &str, options: &PatchOptions) -> Patch {
build(critic, options).0
}
pub fn patch_redline(docx: &[u8], options: &PatchOptions) -> Result<Patch, MarkdownError> {
let package = |error: crate::opc::OpcError| MarkdownError::Package(error.to_string());
let old = reject_revisions(docx).map_err(package)?;
let new = accept_revisions(docx).map_err(package)?;
patch_word(docx, &old, &new, None, options, &MarkdownOptions::default())
}
pub fn patch_own_changes(docx: &[u8], options: &PatchOptions) -> Result<Patch, MarkdownError> {
let changes = crate::changes::list_changes(docx)
.map_err(|error| MarkdownError::Docx(error.to_string()))?;
let others: Vec<String> = changes
.into_iter()
.filter(|c| {
c.author.as_deref() != Some(options.owner.author.as_str())
|| c.date.as_deref() != Some(options.owner.date.as_str())
})
.map(|c| c.id)
.collect();
if others.is_empty() {
return patch_redline(docx, options);
}
let filter = crate::changes::ChangeFilter {
ids: Some(others),
..crate::changes::ChangeFilter::default()
};
let own = crate::changes::accept_elements(docx, &filter)
.map_err(|error| MarkdownError::Package(error.to_string()))?;
patch_redline(&own, options)
}
pub fn patch_documents(
old: Source<'_>,
new: Source<'_>,
redline_options: &RedlineOptions<'_>,
options: &PatchOptions,
) -> Result<Patch, MarkdownError> {
if let (Source::Markdown(old), Source::Markdown(new)) = (old, new) {
return Ok(patch_markdown(old, new, options));
}
let mut compared = redline_options.clone();
compared.settings.author_for_revisions = options.owner.author.clone();
compared.settings.date_time_for_revisions = options.owner.date.clone();
let docx = redline(old, new, &compared)?;
let package = |error: crate::opc::OpcError| MarkdownError::Package(error.to_string());
let old = match old {
Source::Docx(docx) => docx.to_vec(),
Source::Markdown(_) => reject_revisions(&docx).map_err(package)?,
};
let new = match new {
Source::Docx(docx) => docx.to_vec(),
Source::Markdown(_) => accept_revisions(&docx).map_err(package)?,
};
let markdown_options = MarkdownOptions {
input_limits: compared.settings.input_limits,
..MarkdownOptions::default()
};
let known = segments(&docx_to_markdown(&old, &markdown_options)?.markdown)
.into_iter()
.filter_map(|segment| match segment {
Segment::Note(note, _) => Some(note),
_ => None,
})
.collect();
patch_word(&docx, &old, &new, Some(&known), options, &markdown_options)
}
fn patch_word(
docx: &[u8],
old: &[u8],
new: &[u8],
known: Option<&HashSet<String>>,
options: &PatchOptions,
markdown_options: &MarkdownOptions,
) -> Result<Patch, MarkdownError> {
let critic = docx_to_markdown_stories(docx, markdown_options)?.markdown;
let (mut patch, texts) = build_with(&critic, options, known);
let (old, new) = (
word_paragraphs(old, markdown_options.input_limits)?,
word_paragraphs(new, markdown_options.input_limits)?,
);
let mut sides = [Search::new(&old), Search::new(&new)];
for block in texts {
let old_at = sides[0].next(&block.old);
let new_at = sides[1].next(&block.new);
if let Some(hunk) = block.hunk.and_then(|i| patch.hunks.get_mut(i)) {
let at = if hunk.removed { old_at } else { new_at };
if let Some(at) = at {
hunk.at = at;
}
}
}
Ok(patch)
}
struct WordParagraph {
at: Locator,
letters: String,
}
struct Search<'a> {
letters: Vec<&'a str>,
paragraphs: &'a [WordParagraph],
next: usize,
last: usize,
}
impl<'a> Search<'a> {
fn new(paragraphs: &'a [WordParagraph]) -> Self {
Self {
letters: paragraphs.iter().map(|p| p.letters.as_str()).collect(),
paragraphs,
next: 0,
last: 0,
}
}
fn next(&mut self, markdown: &str) -> Option<Locator> {
if !visible(markdown) {
return None;
}
if let Some(found) = find(&letters(&plain(markdown)), &self.letters, self.next) {
self.next = found + 1;
self.last = found;
}
self.paragraphs.get(self.last).map(|p| p.at.clone())
}
}
fn word_paragraphs(
docx: &[u8],
limits: crate::admission::InputLimits,
) -> Result<Vec<WordParagraph>, MarkdownError> {
let error = |error: inspect::InspectError| MarkdownError::Docx(error.to_string());
let (body, stories) = inspect::paragraphs_and_stories_within(docx, limits).map_err(error)?;
let all = body.into_iter().map(|p| ("body".to_string(), p)).chain(
stories
.into_iter()
.flat_map(|s| s.paragraphs.into_iter().map(move |p| (s.id.clone(), p))),
);
Ok(all
.map(|(story, p)| WordParagraph {
at: Locator::Paragraph {
story,
index: p.index,
},
letters: letters(&p.text),
})
.collect())
}
fn find(block: &str, paragraphs: &[&str], from: usize) -> Option<usize> {
let rest = paragraphs.get(from..)?;
let at = |test: &dyn Fn(&str) -> bool| {
rest.iter()
.position(|p| !p.is_empty() && test(p))
.map(|i| from + i)
};
at(&|p| p == block).or_else(|| at(&|p| block.contains(p)))
}
fn letters(text: &str) -> String {
text.chars().filter(|c| c.is_alphanumeric()).collect()
}
fn plain(markdown: &str) -> String {
let markdown = markdown.trim_start_matches('\n');
let mut out = String::new();
let mut rest = &markdown[marker_len(markdown)..];
while let Some(c) = rest.chars().next() {
let skip = if rest.starts_with("](") {
out.push(']');
rest.find(')').map(|end| end + 1)
} else if rest.starts_with("[^") {
rest.find(']').map(|end| end + 1)
} else if c == '<' && rest[1..].starts_with(|c: char| c.is_ascii_alphabetic() || c == '/') {
rest.find('>').map(|end| end + 1)
} else {
None
};
match skip {
Some(length) => rest = &rest[length..],
None => {
out.push(c);
rest = &rest[c.len_utf8()..];
}
}
}
out
}
struct Paragraphs {
hunk: Option<usize>,
old: String,
new: String,
}
fn build(critic: &str, options: &PatchOptions) -> (Patch, Vec<Paragraphs>) {
build_with(critic, options, None)
}
fn build_with(
critic: &str,
options: &PatchOptions,
known: Option<&HashSet<String>>,
) -> (Patch, Vec<Paragraphs>) {
let critic = critic.replace("\r\n", "\n");
let owner = &options.owner;
let authors = super::write::split_front_matter(&critic)
.map(|(yaml, _)| super::view_notes::authors(yaml))
.unwrap_or_default();
let blocks = blocks(detach_breaks(join_marks(attribute(
segments(&critic),
&authors,
owner,
))));
let mut hunks = Vec::new();
let mut texts = Vec::new();
let (mut old_line, mut new_line) = (1, 1);
for block in &blocks {
old_line += newlines(&block.separator, block.old_before_visible);
new_line += newlines(&block.separator, block.new_before_visible);
let (old_text, new_text) = (block.text(Side::Old), block.text(Side::New));
if block.marked(known) {
let (at, removed) = if visible(&new_text) || !visible(&old_text) {
(Locator::Line(new_line), false)
} else {
(Locator::Line(old_line), true)
};
texts.push(Paragraphs {
hunk: Some(hunks.len()),
old: old_text.clone(),
new: new_text.clone(),
});
hunks.push(hunk(block, at, removed, owner));
} else {
texts.push(Paragraphs {
hunk: None,
old: old_text.clone(),
new: new_text.clone(),
});
}
old_line += old_text.matches('\n').count();
new_line += new_text.matches('\n').count();
}
let patch = Patch {
old_name: options.old_name.clone(),
new_name: options.new_name.clone(),
owner: owner.clone(),
hunks,
};
(patch, texts)
}
fn newlines(separator: &str, counted: bool) -> usize {
if counted {
separator.matches('\n').count()
} else {
0
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Side {
Old,
New,
}
#[derive(Clone, Debug, Default)]
struct Edit {
old: String,
new: String,
old_marked: String,
new_marked: String,
by: Option<(String, String)>,
new_by: Option<(String, String)>,
}
impl Edit {
fn push(&mut self, side: Side, text: &str, plain: bool) {
let (plain_text, marked) = match side {
Side::Old => (&mut self.old, &mut self.old_marked),
Side::New => (&mut self.new, &mut self.new_marked),
};
if plain {
plain_text.push_str(text);
}
marked.push_str(text);
}
}
#[derive(Clone, Debug)]
enum Segment {
Same(String),
Edit(Edit),
HighlightStart,
HighlightEnd,
Note(String, bool),
}
fn segments(critic: &str) -> Vec<Segment> {
let mut out: Vec<Segment> = Vec::new();
let mut edit: Option<Edit> = None;
let mut side = Side::New;
let mut note: Option<String> = None;
let mut attribution = false;
let mut paragraph_note = false;
let mut paragraph_break: Option<(String, String)> = None;
let mut held: Vec<String> = Vec::new();
critic::Pieces::default().feed(&critic::encode_spans_only(critic), |piece| match piece {
Piece::Text(mut text) => {
if let Some((tag, mut separator)) = paragraph_break.take() {
while separator.bytes().filter(|&b| b == b'\n').count() < 2 {
let width = if text.starts_with("\r\n") {
2
} else if text.starts_with('\n') {
1
} else {
break;
};
separator.push_str(&text[..width]);
text = &text[width..];
}
if separator.bytes().filter(|&b| b == b'\n').count() == 2 {
let mut boundary = Edit::default();
boundary.push(Side::New, &separator, true);
out.push(Segment::Edit(boundary));
out.push(Segment::Note(tag, true));
} else if text.is_empty() {
paragraph_break = Some((tag, separator));
} else {
push_same(&mut out, &separator);
}
if text.is_empty() {
return;
}
}
if let Some(note) = &mut note {
note.push_str(text);
} else if let Some(edit) = &mut edit {
edit.push(side, text, true);
} else if let Some(Segment::Same(same)) = out.last_mut() {
same.push_str(text);
} else {
out.push(Segment::Same(text.to_string()));
}
}
Piece::Token(token) => match token {
Token::MarkStart
| Token::MarkEnd
| Token::FieldStart
| Token::FieldSeparator
| Token::FieldEnd => {
let text = critic::delimiter(token);
if let Some(note) = &mut note {
note.push_str(text);
} else if let Some(edit) = &mut edit {
edit.push(side, text, false);
} else {
push_same(&mut out, text);
}
}
Token::InsertStart | Token::DeleteStart | Token::SubstituteStart => {
edit = Some(Edit::default());
side = if token == Token::InsertStart {
Side::New
} else {
Side::Old
};
}
Token::SubstituteSeparator => side = Side::New,
Token::InsertEnd | Token::DeleteEnd | Token::SubstituteEnd => {
if let Some(edit) = edit.take() {
out.push(Segment::Edit(edit));
}
out.extend(held.drain(..).map(|text| Segment::Note(text, false)));
}
Token::HighlightStart | Token::HighlightEnd => {
let start = token == Token::HighlightStart;
match &mut edit {
Some(edit) => edit.push(side, if start { "{==" } else { "==}" }, false),
None if start => out.push(Segment::HighlightStart),
None => out.push(Segment::HighlightEnd),
}
}
Token::CommentStart | Token::AttributionStart | Token::ParagraphInsertion => {
attribution = token != Token::CommentStart;
paragraph_note = token == Token::ParagraphInsertion;
note = Some(String::new());
}
Token::CommentBreak => {
if let Some(note) = &mut note {
note.push_str("\n\n");
}
}
Token::CommentEnd | Token::AttributionEnd => {
let text = note.take().unwrap_or_default();
if std::mem::take(&mut paragraph_note) {
paragraph_break = Some((text, String::new()));
return;
}
if edit.is_some() {
held.push(text);
} else {
out.push(Segment::Note(text, attribution));
}
}
},
});
if let Some((_, separator)) = paragraph_break {
push_same(&mut out, &separator);
}
out
}
fn attribute(
segments: Vec<Segment>,
authors: &HashMap<String, super::view_notes::Author>,
owner: &Attribution,
) -> Vec<Segment> {
let mut out: Vec<Segment> = Vec::with_capacity(segments.len());
let mut named_edit = false;
let mut ranged: HashMap<String, (usize, Side)> = HashMap::new();
for segment in segments {
let at = out
.iter()
.rposition(|s| !matches!(s, Segment::Note(..)))
.unwrap_or_default();
if let Segment::Note(text, true) = &segment
&& let Some(Segment::Edit(edit)) = out
.iter_mut()
.rev()
.find(|s| !matches!(s, Segment::Note(..)))
{
if let Some(parts) = super::view_notes::plain_revisions(text.trim())
&& parts.len() == 2
&& !edit.old_marked.is_empty()
&& !edit.new_marked.is_empty()
{
let by = |part: &super::view_notes::PlainRevision| {
(!part.author.is_empty() || !part.date.is_empty())
.then(|| (part.author.clone(), part.date.clone()))
};
edit.by = by(&parts[0]);
edit.new_by = by(&parts[1]);
named_edit = true;
continue;
}
if let Some(tags) = super::view_notes::revision_tags(text.trim()).or_else(|| {
super::view_notes::nested_revision_tags(text.trim())
.map(|nest| nest.into_iter().take(1).collect())
}) && let Some(first) = tags.first()
{
let mut range = |tag: &super::view_notes::Tag, side: Side| {
if tag.date.is_none() && authors.get(&tag.handle).is_some_and(ranged_only) {
ranged.insert(tag.handle.clone(), (at, side));
}
};
let both_sides = !edit.old_marked.is_empty() && !edit.new_marked.is_empty();
if tags.len() == 2 && both_sides {
edit.by = Some(tag_attribution(&tags[0], authors, owner));
edit.new_by = Some(tag_attribution(&tags[1], authors, owner));
range(&tags[0], Side::Old);
range(&tags[1], Side::New);
named_edit = true;
continue;
}
let resolved = Some(tag_attribution(first, authors, owner));
if !named_edit || (!both_sides && edit.by.is_none()) {
edit.by = resolved;
range(
first,
if edit.old_marked.is_empty() {
Side::New
} else {
Side::Old
},
);
named_edit = true;
continue;
}
if both_sides && edit.new_by.is_none() {
edit.new_by = resolved;
range(first, Side::New);
continue;
}
}
let by = if let Some(plain) = super::view_notes::plain_revision(text.trim()) {
Some(
(!plain.author.is_empty() || !plain.date.is_empty())
.then_some((plain.author, plain.date)),
)
} else if let Some((Some(author), date, "")) = named(text.trim()) {
Some(Some((author, date.to_string())))
} else {
None
};
if let Some(by) = by {
let both_sides = !edit.old_marked.is_empty() && !edit.new_marked.is_empty();
if !named_edit || (!both_sides && edit.by.is_none()) {
edit.by = by;
named_edit = true;
continue;
}
if both_sides && edit.new_by.is_none() && by.is_some() {
edit.new_by = by;
continue;
}
}
}
if matches!(segment, Segment::Edit(_)) {
named_edit = false;
}
out.push(segment);
}
for (handle, (at, side)) in ranged {
let Some((_, last)) = authors.get(&handle).and_then(|known| known.range.as_ref()) else {
continue;
};
let Some(Segment::Edit(edit)) = out.get_mut(at) else {
continue;
};
let last = format!("{last}T23:59:59Z");
let both_sides = !edit.old_marked.is_empty() && !edit.new_marked.is_empty();
match side {
Side::New if both_sides => {
if let Some((_, date)) = &mut edit.new_by {
*date = last;
}
}
Side::Old if both_sides && edit.new_by.is_none() => {
edit.new_by = edit.by.clone();
if let Some((_, date)) = &mut edit.by {
*date = last;
}
}
_ => {
if let Some((_, date)) = &mut edit.by {
*date = last;
}
}
}
}
out
}
fn ranged_only(known: &super::view_notes::Author) -> bool {
known.range.is_some() && known.date.is_none() && known.latest.is_none()
}
fn tag_attribution(
tag: &super::view_notes::Tag,
authors: &HashMap<String, super::view_notes::Author>,
owner: &Attribution,
) -> (String, String) {
let known = authors.get(&tag.handle);
let author = match known {
_ if tag.handle == super::view_notes::UNNAMED => String::new(),
Some(person) => person.name.clone(),
None => owner.author.clone(),
};
if let Some(date) = &tag.date {
return (author, date.clone());
}
let date = match known {
Some(person) => person
.date
.clone()
.or_else(|| person.latest.clone())
.or_else(|| {
person
.range
.as_ref()
.map(|(first, _)| format!("{first}T00:00:00Z"))
})
.unwrap_or_default(),
None if tag.handle == super::view_notes::UNNAMED => String::new(),
None => owner.date.clone(),
};
(author, date)
}
fn one_side(edit: &Edit) -> Option<(Side, bool)> {
match (edit.old.is_empty(), edit.new.is_empty()) {
(false, true) => Some((Side::Old, edit.old.trim().is_empty())),
(true, false) => Some((Side::New, edit.new.trim().is_empty())),
_ => None,
}
}
fn join_marks(segments: Vec<Segment>) -> Vec<Segment> {
let mut out: Vec<Segment> = Vec::with_capacity(segments.len());
for segment in segments {
if let Segment::Edit(edit) = &segment
&& let Some((side, mark)) = one_side(edit)
&& let Some(Segment::Edit(before)) = out
.iter_mut()
.rev()
.find(|s| !matches!(s, Segment::Note(..)))
&& let Some((before_side, _)) = one_side(before)
&& before_side == side
&& before.by == edit.by
&& (mark
|| match side {
Side::Old => before.old.ends_with('\n'),
Side::New => before.new.ends_with('\n'),
})
{
match side {
Side::Old => {
before.old.push_str(&edit.old);
before.old_marked.push_str(&edit.old_marked);
}
Side::New => {
before.new.push_str(&edit.new);
before.new_marked.push_str(&edit.new_marked);
}
}
continue;
}
out.push(segment);
}
out
}
fn detach_breaks(segments: Vec<Segment>) -> Vec<Segment> {
fn same(out: &mut Vec<Segment>, text: &str) {
match out.last_mut() {
Some(Segment::Same(same)) => same.push_str(text),
_ => out.push(Segment::Same(text.to_string())),
}
}
fn starts_paragraph(out: &[Segment]) -> bool {
for segment in out.iter().rev() {
match segment {
Segment::Same(text) => match text.rsplit_once('\n') {
Some((_, line)) => return !visible(line),
None if visible(text) => return false,
None => {}
},
Segment::Edit(_) => return false,
_ => {}
}
}
true
}
let leads = leading_breaks(&segments);
let mut out: Vec<Segment> = Vec::with_capacity(segments.len());
let mut after: Option<String> = None;
for (at, segment) in segments.into_iter().enumerate() {
if !matches!(segment, Segment::Note(..))
&& let Some(text) = after.take()
{
same(&mut out, &text);
}
let Segment::Edit(mut edit) = segment else {
match segment {
Segment::Same(text) => same(&mut out, &text),
other => out.push(other),
}
continue;
};
let side = match (edit.old.is_empty(), edit.new.is_empty()) {
(false, true) => Side::Old,
(true, false) => Side::New,
_ => {
out.push(Segment::Edit(edit));
continue;
}
};
let (plain, marked) = match side {
Side::Old => (&mut edit.old, &mut edit.old_marked),
Side::New => (&mut edit.new, &mut edit.new_marked),
};
let trailing = plain.len() - plain.trim_end_matches('\n').len();
let leading = plain.len() - plain.trim_start_matches('\n').len();
if leads.contains(&at) {
same(&mut out, plain);
} else if plain.trim().is_empty() {
out.push(Segment::Edit(edit));
} else if trailing >= 2
&& marked.ends_with(&plain[plain.len() - trailing..])
&& starts_paragraph(&out)
{
let text = plain.split_off(plain.len() - trailing);
marked.truncate(marked.len() - trailing);
out.push(Segment::Edit(edit));
after = Some(text);
} else if leading >= 2 && marked.starts_with(&plain[..leading]) {
let text: String = plain.drain(..leading).collect();
marked.drain(..leading);
same(&mut out, &text);
out.push(Segment::Edit(edit));
} else {
out.push(Segment::Edit(edit));
}
}
if let Some(text) = after {
same(&mut out, &text);
}
out
}
fn leading_breaks(segments: &[Segment]) -> HashSet<usize> {
fn one_side(segment: &Segment) -> Option<(Side, &str, Option<&str>)> {
let Segment::Edit(edit) = segment else {
return None;
};
let author = edit.by.as_ref().map(|(author, _)| author.as_str());
match (edit.old.is_empty(), edit.new.is_empty()) {
(false, true) => Some((Side::Old, edit.old.as_str(), author)),
(true, false) => Some((Side::New, edit.new.as_str(), author)),
_ => None,
}
}
fn in_paragraph(text: &str) -> bool {
text.match_indices('\n')
.all(|(at, _)| text[..at].ends_with('\\'))
}
let next =
|from: usize| (from..segments.len()).find(|&i| !matches!(segments[i], Segment::Note(..)));
let mut out = HashSet::new();
for (at, segment) in segments.iter().enumerate() {
let Some((side, plain, author)) = one_side(segment) else {
continue;
};
if !plain.trim().is_empty() || !plain.contains("\n\n") {
continue;
}
let mut cursor = next(at + 1);
let mut text = false;
while let Some(piece) = cursor
&& let Some((piece_side, piece_text, piece_author)) = one_side(&segments[piece])
&& piece_side == side
&& piece_author == author
&& in_paragraph(piece_text)
{
text |= !piece_text.trim().is_empty();
cursor = next(piece + 1);
}
if !text {
continue;
}
let ends = match cursor.map(|i| &segments[i]) {
None => true,
Some(Segment::Same(after)) => after.starts_with('\n'),
Some(after) => {
one_side(after).is_some_and(|(s, t, _)| s == side && t.starts_with("\n\n"))
}
};
if ends {
out.insert(at);
}
}
out
}
struct Block {
separator: String,
old_before_visible: bool,
new_before_visible: bool,
segments: Vec<Segment>,
}
impl Block {
fn text(&self, side: Side) -> String {
let mut out = String::new();
for segment in &self.segments {
match segment {
Segment::Same(text) => out.push_str(text),
Segment::Edit(edit) => out.push_str(match side {
Side::Old => &edit.old,
Side::New => &edit.new,
}),
_ => {}
}
}
out
}
fn marked(&self, known: Option<&HashSet<String>>) -> bool {
self.segments.iter().any(|s| match (s, known) {
(Segment::Same(_), _) => false,
(Segment::Edit(_), _) | (_, None) => true,
(Segment::Note(note, _), Some(known)) => !known.contains(note),
(_, Some(_)) => false,
})
}
}
fn blocks(segments: Vec<Segment>) -> Vec<Block> {
let mut out: Vec<Block> = Vec::new();
let mut current: Vec<Segment> = Vec::new();
let mut separator = String::new();
let mut line = String::new();
let mut visible = (true, true);
let mut close = |current: &mut Vec<Segment>, separator: &mut String, out: &mut Vec<Block>| {
let block = Block {
separator: std::mem::take(separator),
old_before_visible: visible.0,
new_before_visible: visible.1,
segments: std::mem::take(current),
};
visible = (
self::visible(&block.text(Side::Old)),
self::visible(&block.text(Side::New)),
);
out.push(block);
};
for segment in segments {
let Segment::Same(text) = segment else {
if let Segment::Edit(edit) = &segment {
match edit.new.rfind('\n') {
Some(at) => line = edit.new[at + 1..].to_string(),
None => line.push_str(&edit.new),
}
}
current.push(segment);
continue;
};
let mut rest = text.as_str();
while let Some(at) = rest.find('\n') {
let before = &rest[..at];
if !before.is_empty() {
push_same(&mut current, before);
}
line.push_str(before);
let after = &rest[at + 1..];
let next = after.split('\n').next().unwrap_or("");
let boundary = next.trim().is_empty() || !open_paragraph(&line) || !continues(next);
if boundary {
if current.is_empty() {
separator.push('\n');
} else {
close(&mut current, &mut separator, &mut out);
separator.push('\n');
}
} else if current.is_empty() {
separator.push('\n');
} else {
push_same(&mut current, "\n");
}
line.clear();
rest = after;
}
if !rest.is_empty() {
push_same(&mut current, rest);
line.push_str(rest);
}
}
if !current.is_empty() {
close(&mut current, &mut separator, &mut out);
}
out
}
fn visible(text: &str) -> bool {
let text = text.trim_start();
if table_row(text) {
return text
.chars()
.any(|c| !matches!(c, '|' | '-' | ':') && !c.is_whitespace());
}
!text[marker_len(text)..].trim().is_empty()
}
fn push_same(segments: &mut Vec<Segment>, text: &str) {
if let Some(Segment::Same(same)) = segments.last_mut() {
same.push_str(text);
} else {
segments.push(Segment::Same(text.to_string()));
}
}
fn comment(text: &str, owner: &Attribution, on: Option<String>) -> Comment {
let trimmed = text.trim();
if let Some((Some(author), date, rest)) = named(trimmed)
&& let Some(body) = rest.strip_prefix(':').or(rest.is_empty().then_some(""))
{
return Comment {
author,
date: date.to_string(),
text: body.trim().to_string(),
on,
};
}
Comment {
author: owner.author.clone(),
date: owner.date.clone(),
text: trimmed.to_string(),
on,
}
}
fn hunk(block: &Block, at: Locator, removed: bool, owner: &Attribution) -> Hunk {
let mut text = String::new();
let mut changes: Vec<Change> = Vec::new();
let mut comments = Vec::new();
let mut highlight: Option<String> = None;
let mut highlighted: Option<String> = None;
let mut previous: Option<&Segment> = None;
for segment in &block.segments {
match segment {
Segment::Same(same) => {
text.push_str(&escape(same));
if let Some(h) = &mut highlight {
h.push_str(same);
}
}
Segment::Edit(edit) => {
let named = |text: &mut String, by: &Option<(String, String)>| match by {
Some((author, date)) => {
if author != &owner.author || date != &owner.date {
text.push_str(&format!("{{>>{author} ({date})<<}}"));
}
(author.clone(), date.clone())
}
None => (owner.author.clone(), owner.date.clone()),
};
let mut sides = Vec::with_capacity(2);
match &edit.new_by {
Some(_) => {
text.push_str(&format!("[-{}-]", escape(&edit.old_marked)));
sides.push((edit.old.clone(), String::new(), named(&mut text, &edit.by)));
text.push_str(&format!("{{+{}+}}", escape(&edit.new_marked)));
sides.push((
String::new(),
edit.new.clone(),
named(&mut text, &edit.new_by),
));
}
None => {
if !edit.old_marked.is_empty() {
text.push_str(&format!("[-{}-]", escape(&edit.old_marked)));
}
if !edit.new_marked.is_empty() {
text.push_str(&format!("{{+{}+}}", escape(&edit.new_marked)));
}
sides.push((
edit.old.clone(),
edit.new.clone(),
named(&mut text, &edit.by),
));
}
}
if let Some(h) = &mut highlight {
h.push_str(&edit.new);
}
changes.extend(sides.into_iter().map(|(old, new, (author, date))| Change {
old,
new,
author,
date,
comment: None,
}));
}
Segment::HighlightStart => {
text.push_str("{==");
highlight = Some(String::new());
}
Segment::HighlightEnd => {
text.push_str("==}");
highlighted = highlight.take();
}
Segment::Note(note, _) => {
let on = match previous {
Some(Segment::HighlightEnd) => highlighted.take(),
_ => None,
};
let comment = comment(note, owner, on);
text.push_str(&format!(
"{{>>{} ({}): {}<<}}",
comment.author, comment.date, comment.text
));
match (previous, changes.last_mut()) {
(Some(Segment::Edit(edit)), Some(change))
if change.comment.is_none()
&& edit
.new_by
.as_ref()
.or(edit.by.as_ref())
.is_none_or(|(a, d)| a == &owner.author && d == &owner.date) =>
{
change.comment = Some(comment);
}
_ => comments.push(comment),
}
}
}
previous = Some(segment);
}
Hunk {
at,
removed,
text,
changes,
comments,
}
}
fn escape(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut backslashes = 0;
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
let next = chars.peek().copied();
match (c, next) {
('[', Some('-')) | ('{', Some('+')) if backslashes % 2 == 0 => out.push('\\'),
_ => {}
}
out.push(c);
match (c, next) {
('-', Some(']')) | ('+', Some('}')) => out.push('\\'),
_ => {}
}
backslashes = if c == '\\' { backslashes + 1 } else { 0 };
}
out
}
fn wrap(text: &str, columns: usize) -> String {
let mut out: Vec<String> = Vec::new();
let mut fenced = false;
for line in text.split('\n') {
let trimmed = line.trim_start();
let fence = trimmed.starts_with("```") || trimmed.starts_with("~~~");
let keep = columns == 0
|| fenced
|| fence
|| trimmed.starts_with('#')
|| table_row(line)
|| line.chars().count() <= columns;
if fence {
fenced = !fenced;
}
if keep {
out.push(line.to_string());
} else {
out.extend(break_line(line, columns).into_iter().map(str::to_string));
}
}
out.join("\n")
}
fn break_line(line: &str, columns: usize) -> Vec<&str> {
let protected = protected(line);
let breaks: Vec<usize> = line
.char_indices()
.filter(|&(at, c)| c == ' ' && can_break(line, at, &protected))
.map(|(at, _)| at)
.collect();
let mut out = Vec::new();
let mut start = 0;
loop {
let width = |end: usize| line[start..end].chars().count();
if width(line.len()) <= columns {
break;
}
let candidates = breaks.iter().copied().filter(|&b| b > start);
let fitting = candidates
.clone()
.take_while(|&b| width(b) <= columns)
.last();
let Some(at) = fitting.or_else(|| candidates.clone().next()) else {
break;
};
out.push(&line[start..at]);
start = at + 1;
}
out.push(&line[start..]);
out
}
fn protected(line: &str) -> Vec<(usize, usize)> {
let bytes = line.as_bytes();
let mut out = Vec::new();
let mut at = 0;
while at < bytes.len() {
match bytes[at] {
b'\\' => at += 2,
b'`' => {
let run = bytes[at..].iter().take_while(|b| **b == b'`').count();
let fence = &line[at..at + run];
let mut end = at + run;
let mut closed = None;
while let Some(found) = line[end..].find(fence) {
let start = end + found;
let length = bytes[start..].iter().take_while(|b| **b == b'`').count();
if length == run {
closed = Some(start + run);
break;
}
end = start + length;
}
match closed {
Some(close) => {
out.push((at, close));
at = close;
}
None => at += run,
}
}
b']' if bytes.get(at + 1) == Some(&b'(') => {
let mut depth = 0;
let mut end = at + 1;
while end < bytes.len() {
match bytes[end] {
b'(' => depth += 1,
b')' => {
depth -= 1;
if depth == 0 {
break;
}
}
b'\\' => end += 1,
_ => {}
}
end += 1;
}
out.push((at, end.min(bytes.len())));
at = end + 1;
}
b'<' if line[at + 1..].starts_with("http") || line[at + 1..].starts_with("mailto:") => {
let end = line[at..].find('>').map_or(bytes.len(), |e| at + e + 1);
out.push((at, end));
at = end;
}
_ => at += 1,
}
}
out
}
const OPENERS: [&str; 4] = ["[-", "{+", "{==", "{>>"];
const CLOSERS: [&str; 4] = ["-]", "+}", "==}", "<<}"];
fn can_break(line: &str, at: usize, protected: &[(usize, usize)]) -> bool {
if protected.iter().any(|&(start, end)| start < at && at < end) {
return false;
}
let before = &line[..at];
let after = &line[at + 1..];
if before.is_empty()
|| before.ends_with([' ', '\\'])
|| after.is_empty()
|| after.starts_with(' ')
{
return false;
}
if OPENERS.iter().any(|m| before.ends_with(m)) || CLOSERS.iter().any(|m| after.starts_with(m)) {
return false;
}
!starts_block(after)
}
fn starts_block(text: &str) -> bool {
let word = text.split(' ').next().unwrap_or("");
marker_len(text) > 0
|| text.starts_with(['|', '>', '#', '<'])
|| text.starts_with("```")
|| text.starts_with("~~~")
|| (!word.is_empty() && word.chars().all(|c| c == '=' || c == '-'))
|| (word.len() > 1 && word.chars().all(|c| c == '*' || c == '_'))
|| (word.ends_with(['.', ')'])
&& word[..word.len() - 1].bytes().all(|b| b.is_ascii_digit())
&& word.len() > 1)
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod tests {
use super::*;
#[test]
fn a_wrap_never_strands_a_change_marker() {
let line = "**This document [-shows-]{+demonstrates+} Heading 1 {+paragraph +}style[- with extra bold emphasis-].** {==see==}{>>note <<} end";
for columns in [20, 40, 56, 60, 72] {
let wrapped = wrap(line, columns);
assert_eq!(wrapped.replace('\n', " "), line, "{columns}");
for row in wrapped.lines() {
for close in ["+}", "-]", "==}", "<<}"] {
assert!(
!row.starts_with(close),
"{columns}: {row:?} starts with {close}"
);
}
for open in ["{+", "[-", "{==", "{>>"] {
assert!(!row.ends_with(open), "{columns}: {row:?} ends with {open}");
}
}
}
}
#[test]
fn escapes_only_unescaped_delimiters() {
assert_eq!(escape("a [-b-] {+c+}"), "a \\[-b-\\] \\{+c+\\}");
assert_eq!(escape("\\[-b"), "\\[-b");
assert_eq!(escape("x-y [z]"), "x-y [z]");
}
#[test]
fn protects_code_links_and_autolinks() {
let line = "a `b c` [d](e f) <http://g h>";
let ranges = protected(line);
assert_eq!(ranges.len(), 3, "{ranges:?}");
assert!(!can_break(line, line.find(" c`").unwrap(), &ranges));
assert!(!can_break(line, line.find(" f)").unwrap(), &ranges));
assert!(can_break(line, 1, &ranges));
}
#[test]
fn a_numbered_note_after_a_change_names_its_author_never_a_comment() {
let owner = Attribution {
author: "Owner".to_string(),
date: "2026-01-01T00:00:00Z".to_string(),
};
let by = |critic: &str| {
attribute(segments(critic), &HashMap::new(), &owner)
.into_iter()
.map(|segment| match segment {
Segment::Edit(edit) => format!("edit {:?}", edit.by),
Segment::Note(note, _) => format!("note {note}"),
_ => String::new(),
})
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
};
let ana = Some(("Ana Lima".to_string(), "2026-09-30T14:05:00Z".to_string()));
assert_eq!(
by("a {++b++}{r3 Ana Lima (2026-09-30T14:05:00Z)} c"),
[format!("edit {ana:?}")]
);
assert_eq!(
by("a {++b++}{footnotes.r3+4 Ana Lima (2026-09-30T14:05:00Z)}"),
[format!("edit {ana:?}")]
);
assert_eq!(
by("a {++b++}{noid Ana Lima (2026-09-30T14:05:00Z)}"),
[format!("edit {ana:?}")]
);
assert_eq!(by("a {++b++}{r3}"), ["edit None"]);
assert_eq!(
by("a {++b++}{>>Ana Lima (2026-09-30T14:05:00Z): why<<}"),
["edit None", "note Ana Lima (2026-09-30T14:05:00Z): why"]
);
}
#[test]
fn plain_text_drops_markers_targets_note_references_and_tags() {
assert_eq!(plain("- a<u>b</u>c [d](e)[^1] x < y"), "abc [d] x < y");
}
#[test]
fn no_line_starts_a_block() {
for text in [
"- x", "* x", "+ x", "1. x", "12) x", "# x", "> x", "| x", "=== x", "--- x", "```",
"<div>",
] {
assert!(starts_block(text), "{text}");
}
for text in ["x", "1.5 x", "-5 x", "word"] {
assert!(!starts_block(text), "{text}");
}
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod literal_wrapping_boundary_tests {
use super::*;
#[test]
fn protected_source_ranges_keep_exact_code_target_and_autolink_owners() {
for (source, owned) in [
("before ``one ` two`` after", "``one ` two``"),
("before `one `` two` after", "`one `` two`"),
(
"before [label](outer(inner) tail) after",
"](outer(inner) tail",
),
(r"before [label](escaped\) tail) after", r"](escaped\) tail"),
("before [label](unterminated tail", "](unterminated tail"),
("before <mailto:one two> after", "<mailto:one two>"),
("before <https://one two", "<https://one two"),
] {
let ranges = protected(source);
assert_eq!(ranges.len(), 1, "{source}");
assert_eq!(&source[ranges[0].0..ranges[0].1], owned, "{source}");
for (at, c) in source
.char_indices()
.filter(|(at, c)| *c == ' ' && ranges[0].0 < *at && *at < ranges[0].1)
{
assert_eq!(c, ' ');
assert!(!can_break(source, at, &ranges));
}
let wrapped = wrap(source, 8);
assert_eq!(wrapped.replace('\n', " "), source);
assert!(wrapped.contains(owned));
}
for source in [
"before `unclosed tail",
r"before \`literal tail",
"before <ordinary tail>",
r"before [label]\(literal tail)",
] {
assert!(protected(source).is_empty(), "{source}");
assert_eq!(wrap(source, 8).replace('\n', " "), source);
}
}
#[test]
fn exact_markdown_break_guards_preserve_literal_whitespace_and_block_markers() {
for source in [" leading", "trailing ", "double space", r"escaped\ space"] {
for (at, _) in source.char_indices().filter(|(_, c)| *c == ' ') {
assert!(!can_break(source, at, &[]), "{source:?} at {at}");
}
}
for marker in ["[-", "{+", "{==", "{>>"] {
let source = format!("{marker} text");
assert!(!can_break(&source, marker.len(), &[]));
}
for marker in ["-]", "+}", "==}", "<<}"] {
let source = format!("text {marker}");
assert!(!can_break(&source, 4, &[]));
}
for (suffix, starts) in [
("*** text", true),
("__ text", true),
("~~~", true),
("12) text", true),
("1x. text", false),
(". text", false),
("a*b text", false),
("=x text", false),
("", false),
] {
assert_eq!(starts_block(suffix), starts, "{suffix}");
let source = format!("owned {suffix}");
assert_eq!(
can_break(&source, 5, &[]),
!starts && !suffix.is_empty(),
"{suffix}"
);
}
assert_eq!(wrap("αβ γδ εζ", 5), "αβ γδ\nεζ");
assert_eq!(wrap("unbreakable", 1), "unbreakable");
assert_eq!(wrap("a b c", 0), "a b c");
let fenced = "~~~rust\nowned very long source\n~~~\na b c";
assert_eq!(
wrap(fenced, 3),
"~~~rust\nowned very long source\n~~~\na b\nc"
);
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod review_tests {
use super::*;
#[test]
fn review_paragraph_tag_keeps_an_incomplete_trailing_separator() {
let text = segments("A¶{r1 Alice}\n")
.into_iter()
.filter_map(|segment| match segment {
Segment::Same(text) => Some(text),
_ => None,
})
.collect::<String>();
assert_eq!(text, "A\n");
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod attribution_branch_tests {
use super::super::view_notes::Author;
use super::*;
const D1: &str = "2026-01-02T03:04:05Z";
const D2: &str = "2026-02-03T04:05:06Z";
fn owner() -> Attribution {
Attribution {
author: "Owner".to_string(),
date: "2026-01-01T00:00:00Z".to_string(),
}
}
fn change(old: &str, new: &str) -> Segment {
let mut edit = Edit::default();
if !old.is_empty() {
edit.push(Side::Old, old, true);
}
if !new.is_empty() {
edit.push(Side::New, new, true);
}
Segment::Edit(edit)
}
fn tag(text: &str) -> Segment {
Segment::Note(text.to_string(), true)
}
fn who(author: &str, date: &str) -> Option<(String, String)> {
Some((author.to_string(), date.to_string()))
}
type By = (Option<(String, String)>, Option<(String, String)>);
fn run(segments: Vec<Segment>, authors: &HashMap<String, Author>) -> (Vec<By>, Vec<String>) {
let mut edits = Vec::new();
let mut notes = Vec::new();
for segment in attribute(segments, authors, &owner()) {
match segment {
Segment::Edit(edit) => edits.push((edit.by, edit.new_by)),
Segment::Note(text, _) => notes.push(text),
_ => {}
}
}
(edits, notes)
}
fn authors() -> HashMap<String, Author> {
HashMap::from([
(
"AL".to_string(),
Author {
name: "Ana Lima".to_string(),
date: None,
latest: None,
range: Some(("2026-03-02".to_string(), "2026-03-04".to_string())),
},
),
(
"BO".to_string(),
Author {
name: "Ben Ode".to_string(),
date: Some(D1.to_string()),
latest: None,
range: None,
},
),
(
"LT".to_string(),
Author {
name: "Lia Tam".to_string(),
date: None,
latest: Some(D2.to_string()),
range: Some(("2026-03-02".to_string(), "2026-03-04".to_string())),
},
),
(
"ND".to_string(),
Author {
name: "No Date".to_string(),
date: None,
latest: None,
range: None,
},
),
])
}
#[test]
fn two_plain_parts_name_each_side_of_a_substitution_only() {
let none = HashMap::new();
let (edits, notes) = run(
vec![
change("a", "b"),
tag(&format!("r1 Ana Lima ({D1}); r2 ({D2})")),
],
&none,
);
assert_eq!(edits, [(who("Ana Lima", D1), who("", D2))]);
assert!(notes.is_empty());
let (edits, _) = run(vec![change("a", "b"), tag("r1; r2")], &none);
assert_eq!(edits, [(None, None)]);
for one_sided in [change("", "b"), change("a", "")] {
let (edits, notes) = run(
vec![
one_sided,
tag(&format!("r1 Ana Lima ({D1}); r2 Ben ({D2})")),
],
&none,
);
assert_eq!(edits, [(None, None)]);
assert_eq!(notes, [format!("r1 Ana Lima ({D1}); r2 Ben ({D2})")]);
}
}
#[test]
fn agent_tags_resolve_through_the_authors_table() {
let table = authors();
let (edits, _) = run(vec![change("a", "b"), tag("r1 @BO; r2 @AL")], &table);
assert_eq!(
edits,
[(who("Ben Ode", D1), who("Ana Lima", "2026-03-04T23:59:59Z"))]
);
let (edits, _) = run(vec![change("a", "b"), tag("r1 @AL")], &table);
assert_eq!(
edits,
[(
who("Ana Lima", "2026-03-04T23:59:59Z"),
who("Ana Lima", "2026-03-02T00:00:00Z")
)]
);
let (edits, _) = run(vec![change("", "b"), tag("r1 @AL")], &table);
assert_eq!(edits, [(who("Ana Lima", "2026-03-04T23:59:59Z"), None)]);
let (edits, _) = run(vec![change("", "b"), tag(&format!("r1 @AL {D2}"))], &table);
assert_eq!(edits, [(who("Ana Lima", D2), None)]);
let (edits, _) = run(vec![change("", "b"), tag("r1 @LT")], &table);
assert_eq!(edits, [(who("Lia Tam", D2), None)]);
let (edits, _) = run(
vec![
change("", "b"),
tag("r1 @ND"),
change("", "c"),
tag("r2 @ZZ"),
change("", "d"),
tag("r3 @??"),
],
&table,
);
assert_eq!(
edits,
[
(who("No Date", ""), None),
(who("Owner", "2026-01-01T00:00:00Z"), None),
(who("", ""), None),
]
);
let (edits, _) = run(vec![change("", "b"), tag("r1 @BO; r2 @ND")], &table);
assert_eq!(edits, [(who("Ben Ode", D1), None)]);
let (edits, _) = run(vec![change("a", ""), tag("r3 @BO re r1 @ND")], &table);
assert_eq!(edits, [(who("Ben Ode", D1), None)]);
}
#[test]
fn later_tags_fill_the_open_side_or_stay_notes() {
let table = authors();
let (edits, notes) = run(
vec![
change("a", "b"),
tag("r1 @BO"),
tag("r2 @AL"),
tag("r3 @ND"),
],
&table,
);
assert_eq!(
edits,
[(who("Ben Ode", D1), who("Ana Lima", "2026-03-04T23:59:59Z"))]
);
assert_eq!(notes, ["r3 @ND"]);
let (edits, _) = run(vec![change("", "b"), tag("r3"), tag("r4 @BO")], &table);
assert_eq!(edits, [(who("Ben Ode", D1), None)]);
let (edits, notes) = run(vec![change("", "b"), tag("r1 @BO"), tag("r2 @ND")], &table);
assert_eq!(edits, [(who("Ben Ode", D1), None)]);
assert_eq!(notes, ["r2 @ND"]);
}
#[test]
fn plain_and_named_notes_fill_sides_in_order() {
let none = HashMap::new();
let (edits, notes) = run(
vec![
change("a", "b"),
tag(&format!("r1 Ana Lima ({D1})")),
tag(&format!("r2 Ben Ode ({D2})")),
tag("r3"),
],
&none,
);
assert_eq!(edits, [(who("Ana Lima", D1), who("Ben Ode", D2))]);
assert_eq!(notes, ["r3"]);
let (edits, _) = run(
vec![change("", "b"), tag(&format!("Ana Lima ({D1})"))],
&none,
);
assert_eq!(edits, [(who("Ana Lima", D1), None)]);
let (edits, notes) = run(
vec![
change("", "b"),
tag(&format!("({D1})")),
tag(&format!("Ana Lima ({D1}): why")),
],
&none,
);
assert_eq!(edits, [(None, None)]);
assert_eq!(notes.len(), 2);
let (edits, notes) = run(
vec![
change("a", "b"),
tag(&format!("r1 Ana Lima ({D1})")),
tag("r2"),
],
&none,
);
assert_eq!(edits, [(who("Ana Lima", D1), None)]);
assert_eq!(notes, ["r2"]);
let (edits, _) = run(
vec![
change("a", ""),
tag("r2"),
tag(&format!("r3 Ben Ode ({D2})")),
],
&none,
);
assert_eq!(edits, [(who("Ben Ode", D2), None)]);
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod segment_branch_tests {
use super::*;
fn show(segments: &[Segment]) -> Vec<String> {
segments
.iter()
.map(|s| match s {
Segment::Same(t) => format!("S:{t}"),
Segment::Edit(e) => {
format!("E:{}|{}|{}|{}", e.old, e.new, e.old_marked, e.new_marked)
}
Segment::Note(t, a) => format!("N:{t}:{a}"),
Segment::HighlightStart => "H<".to_string(),
Segment::HighlightEnd => "H>".to_string(),
})
.collect()
}
fn insert(text: &str) -> Segment {
let mut edit = Edit::default();
edit.push(Side::New, text, true);
Segment::Edit(edit)
}
fn delete(text: &str) -> Segment {
let mut edit = Edit::default();
edit.push(Side::Old, text, true);
Segment::Edit(edit)
}
fn marked_insert(plain: &str, marked: &str) -> Segment {
Segment::Edit(Edit {
new: plain.to_string(),
new_marked: marked.to_string(),
..Edit::default()
})
}
fn by(segment: Segment, author: &str) -> Segment {
match segment {
Segment::Edit(mut edit) => {
edit.by = Some((author.to_string(), String::new()));
Segment::Edit(edit)
}
other => other,
}
}
#[test]
fn highlight_marks_are_text_in_plain_runs_changes_and_comments() {
assert_eq!(show(&segments("a ==b== c")), ["S:a ==b== c"]);
assert_eq!(
show(&segments("x {++y ==z== w++} {>>see ==q==<<}")),
["S:x ", "E:|y z w||y ==z== w", "S: ", "N:see ==q==:false"]
);
}
#[test]
fn a_paragraph_tag_owns_the_separator_after_it() {
assert_eq!(
show(&segments("a¶{r1 @AL}\n\nb")),
["S:a", "E:|\n\n||\n\n", "N:r1 @AL:true", "S:b"]
);
assert_eq!(
show(&segments("a¶{r1 @AL}\r\n\r\nb")),
["S:a", "E:|\r\n\r\n||\r\n\r\n", "N:r1 @AL:true", "S:b"]
);
assert_eq!(show(&segments("a¶{r1 @AL}b")), ["S:ab"]);
assert_eq!(show(&segments("a¶{r1 @AL}\n")), ["S:a\n"]);
}
#[test]
fn detach_breaks_moves_paragraph_marks_out_of_whole_paragraph_changes() {
assert_eq!(
show(&detach_breaks(vec![insert("Para.\n\n")])),
["E:|Para.||Para.", "S:\n\n"]
);
assert_eq!(
show(&detach_breaks(vec![
Segment::Same("x".into()),
insert("Para.\n\n")
])),
["S:x", "E:|Para.\n\n||Para.\n\n"]
);
assert_eq!(
show(&detach_breaks(vec![marked_insert(
"Para.\n\n",
"Para.\n\n=="
)])),
["E:|Para.\n\n||Para.\n\n=="]
);
assert_eq!(
show(&detach_breaks(vec![
Segment::Same("a".into()),
delete("\n\nGone")
])),
["S:a\n\n", "E:Gone||Gone|"]
);
assert_eq!(
show(&detach_breaks(vec![marked_insert("\n\nNew", "==\n\nNew")])),
["E:|\n\nNew||==\n\nNew"]
);
}
#[test]
fn leading_breaks_need_a_whole_same_side_paragraph_after_them() {
let note = || Segment::Note("r1 @AL".into(), true);
assert_eq!(
leading_breaks(&[insert("\n\n"), note(), insert("Para.")]),
HashSet::from([0])
);
assert!(leading_breaks(&[insert("\n\n"), delete("x")]).is_empty());
assert!(leading_breaks(&[insert("\n\n"), by(insert("Para."), "Bo")]).is_empty());
assert_eq!(
leading_breaks(&[insert("\n\n"), insert("one\\\ntwo")]),
HashSet::from([0])
);
assert!(leading_breaks(&[insert("\n\n"), insert("one\ntwo")]).is_empty());
assert_eq!(
leading_breaks(&[insert("\n\n"), insert("P"), insert("\n\nQ")]),
HashSet::from([0])
);
assert!(leading_breaks(&[insert("\n\n"), insert("P"), delete("\n\nQ")]).is_empty());
assert!(
leading_breaks(&[insert("\n\n"), insert("P"), Segment::Same(" tail".into())])
.is_empty()
);
assert_eq!(
leading_breaks(&[insert("\n\n"), insert("P"), Segment::Same("\nnext".into())]),
HashSet::from([0])
);
}
#[test]
fn soft_breaks_inside_a_paragraph_keep_one_block() {
let out = blocks(vec![Segment::Same("\ncontinued\n\nnext".into())]);
assert_eq!(out.len(), 2);
assert_eq!(out[0].separator, "\n");
assert_eq!(out[0].text(Side::New), "continued");
assert_eq!(out[1].separator, "\n\n");
assert_eq!(out[1].text(Side::Old), "next");
}
#[test]
fn comments_need_a_colon_after_the_attribution() {
let owner = Attribution {
author: "Owner".into(),
date: "2026-01-01T00:00:00Z".into(),
};
let named = comment("Ana Lima (2026-02-02T00:00:00Z): why", &owner, None);
assert_eq!(
(named.author.as_str(), named.text.as_str()),
("Ana Lima", "why")
);
let bare = comment("Ana Lima (2026-02-02T00:00:00Z)", &owner, None);
assert_eq!((bare.author.as_str(), bare.text.as_str()), ("Ana Lima", ""));
let text_after = comment("Ana Lima (2026-02-02T00:00:00Z) why", &owner, None);
assert_eq!(text_after.author, "Owner");
assert_eq!(text_after.text, "Ana Lima (2026-02-02T00:00:00Z) why");
}
#[test]
fn tilde_fences_keep_long_code_lines_whole() {
let long = "word ".repeat(20);
let text = format!("~~~\n{long}\n~~~\n{long}");
let wrapped = wrap(&text, 20);
let lines: Vec<&str> = wrapped.lines().collect();
assert_eq!(lines[0], "~~~");
assert_eq!(lines[1], long);
assert_eq!(lines[2], "~~~");
assert!(lines[3..].iter().all(|l| l.chars().count() <= 20));
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod fence_branch_tests {
use super::super::view_notes::Author;
use super::*;
#[test]
fn backtick_fences_keep_their_lines_whole() {
let text = "```\na code line far longer than ten columns\n```\nprose words that wrap";
let wrapped = wrap(text, 10);
assert_eq!(
wrapped,
"```\na code line far longer than ten columns\n```\nprose\nwords that\nwrap"
);
}
#[test]
fn only_a_bare_range_dates_marks_by_range() {
let range = Some(("2026-03-02".to_string(), "2026-03-04".to_string()));
let author = |date: Option<&str>, latest: Option<&str>, range| Author {
name: "A".to_string(),
date: date.map(str::to_string),
latest: latest.map(str::to_string),
range,
};
assert!(ranged_only(&author(None, None, range.clone())));
assert!(!ranged_only(&author(
Some("2026-03-02"),
None,
range.clone()
)));
assert!(!ranged_only(&author(None, Some("2026-03-04"), range)));
assert!(!ranged_only(&author(None, None, None)));
}
}