use super::ooxml::{Inline, Marks};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Mark {
Insertion,
Deletion,
Scope,
}
impl Mark {
pub(crate) fn delimiters(self) -> (&'static str, &'static str) {
match self {
Self::Insertion => ("{++", "++}"),
Self::Deletion => ("{--", "--}"),
Self::Scope => ("{==", "==}"),
}
}
fn index(self) -> usize {
self as usize
}
}
pub(crate) type Change = (Mark, Option<String>);
pub(crate) const TAG: &str = "\u{E000}";
pub(crate) const PLAIN: &str = "\u{E001}";
fn tag(by: Option<&str>) -> Option<&str> {
let by = bare(by?);
by.strip_prefix(TAG)
.or_else(|| by.strip_prefix(PLAIN))
.map(|tagged| tagged.split_once(ON).map_or(tagged, |(own, _)| own))
}
fn outer_of(by: Option<&str>) -> Option<&str> {
let by = bare(by?);
by.strip_prefix(TAG)
.or_else(|| by.strip_prefix(PLAIN))?
.split_once(ON)
.map(|(_, outer)| outer)
}
fn holds(new_by: Option<&str>, old_by: Option<&str>) -> bool {
fn first(tagged: &str) -> &str {
tag_parts(tagged.split(ON).next().unwrap_or(tagged)).0
}
match (tag(new_by), outer_of(old_by)) {
(Some(own), Some(outer)) => super::agent::same_change(first(own), first(outer)),
_ => false,
}
}
const ON: &str = "\u{E002}";
pub(crate) const CARRIED: &str = "\u{E003}";
fn bare(by: &str) -> &str {
by.strip_suffix(CARRIED).unwrap_or(by)
}
pub(super) const MOVE: char = '\u{E004}';
fn sentinel(by: &str) -> &'static str {
if bare(by).starts_with(PLAIN) {
PLAIN
} else {
TAG
}
}
fn tag_parts(tagged: &str) -> (&str, Option<&str>) {
match tagged.split_once(' ') {
Some((t, date)) => (t, Some(date)),
None => (tagged, None),
}
}
pub(super) fn display(by: &str) -> String {
let by = bare(by);
let Some(tagged) = by.strip_prefix(PLAIN).or_else(|| by.strip_prefix(TAG)) else {
return by.to_string();
};
let fold = tagged.contains(ON);
let plain = by.starts_with(PLAIN);
let one = |part: &str| {
let (part, move_name) = strip_move_mark(part);
let printed = if plain {
let printed = super::agent::format_plain_tag(&part);
let printed = if fold {
escaped_author(&printed)
} else {
printed
};
spell_re_in_author(&printed)
} else {
let (t, date) = tag_parts(&part);
let mut out = super::agent::format_tag(t);
if let Some(date) = date {
out.push(' ');
out.push_str(date);
}
out
};
append_move(printed, move_name)
};
tagged.split(ON).map(one).collect::<Vec<_>>().join(" re ")
}
fn strip_move_mark(part: &str) -> (String, Option<&str>) {
let Some(at) = part.find(MOVE) else {
return (part.to_string(), None);
};
let rest = &part[at + MOVE.len_utf8()..];
let end = rest.find([' ', '\u{E002}']).unwrap_or(rest.len());
let mut clean = String::with_capacity(part.len());
clean.push_str(&part[..at]);
clean.push_str(&rest[end..]);
(clean, Some(&rest[..end]))
}
fn append_move(mut printed: String, name: Option<&str>) -> String {
let Some(name) = name else {
return printed;
};
printed.push_str(" move");
if !name.is_empty() {
printed.push(' ');
printed.push_str(name);
}
printed
}
pub(in crate::markdown) fn escaped_author(part: &str) -> String {
let Some((ids, rest)) = part.split_once(' ') else {
return part.to_string();
};
let author_end = super::super::view_notes::trailing_bare_group(rest)
.filter(|&at| super::super::write::is_date(&rest[at + 1..rest.len() - 1]))
.unwrap_or(rest.len());
let mut out = String::with_capacity(part.len());
out.push_str(ids);
out.push(' ');
for c in rest[..author_end].chars() {
match c {
'%' => out.push_str("%25"),
'(' => out.push_str("%28"),
')' => out.push_str("%29"),
'\\' => out.push_str("%5C"),
c => out.push(c),
}
}
out.push_str(&rest[author_end..]);
out
}
pub(in crate::markdown) fn spell_re_in_author(part: &str) -> String {
let Some((ids, rest)) = part.split_once(' ') else {
return part.to_string();
};
let author_end = super::super::view_notes::trailing_bare_group(rest)
.filter(|&at| super::super::write::is_date(&rest[at + 1..rest.len() - 1]))
.unwrap_or(rest.len());
let author = &rest[..author_end];
let spelled = spell_separator_spaces(author);
if spelled == author {
return part.to_string();
}
let mut out = String::with_capacity(part.len() + 2);
out.push_str(ids);
out.push(' ');
out.push_str(&spelled);
out.push_str(&rest[author_end..]);
out
}
fn spell_separator_spaces(author: &str) -> String {
if !author.contains(" re ") {
return author.to_string();
}
let mut out = String::with_capacity(author.len());
let mut rest = author;
while let Some(at) = rest.find(" re ") {
let after = &rest[at + " re ".len()..];
let token = after.split_whitespace().next().unwrap_or("");
if revision_token(token) {
out.push_str(&rest[..at]);
out.push_str("%20re ");
rest = after;
} else {
let keep = at + " re ".len();
out.push_str(&rest[..keep]);
rest = &rest[keep..];
}
}
out.push_str(rest);
out
}
fn revision_token(token: &str) -> bool {
!token.starts_with(|c: char| c.is_ascii_digit())
&& !token.starts_with('#')
&& (token == "noid"
|| token.strip_suffix(".noid").is_some()
|| crate::ids::parse_change_ids(token).is_ok())
}
fn pairable_attribution(a: Option<&str>, b: Option<&str>) -> bool {
use super::agent::{handle_of, split_tag};
match (tag(a), tag(b)) {
(Some(ta), Some(tb)) if a.map(sentinel) == b.map(sentinel) => {
let (own_a, own_b) = (tag_parts(ta).0, tag_parts(tb).0);
let same = if a.is_some_and(|by| sentinel(by) == PLAIN) {
let attribution = |tag| {
crate::markdown::view_notes::plain_revision(&super::agent::format_plain_tag(
tag,
))
.map(|part| (part.author, part.date))
};
attribution(own_a)
.zip(attribution(own_b))
.is_some_and(|(a, b)| a == b)
} else {
handle_of(own_a)
.zip(handle_of(own_b))
.is_some_and(|(a, b)| a == b)
};
same && tag_parts(ta).1 == tag_parts(tb).1 && split_tag(own_a).0 == split_tag(own_b).0
}
_ => a == b,
}
}
fn one_change(old_by: Option<&str>, new_by: Option<&str>) -> bool {
match (tag(old_by), tag(new_by)) {
(Some(old), Some(new)) => super::agent::one_replacement(tag_parts(old).0, tag_parts(new).0),
_ => true,
}
}
fn same_nest(old_by: Option<&str>, new_by: Option<&str>) -> bool {
match outer_of(new_by) {
None => true,
Some(new) => outer_of(old_by) == Some(new),
}
}
fn join_tagged(a: &str, b: &str) -> String {
let kind = sentinel(a);
let (ta, da) = tag_parts(tag(Some(a)).unwrap_or(a));
let (tb, db) = tag_parts(tag(Some(b)).unwrap_or(b));
let mut out = format!(
"{kind}{}",
super::agent::join_tags(&[ta.to_string(), tb.to_string()])
);
if let Some(date) = da.or(db) {
out.push(' ');
out.push_str(date);
}
if let Some(outer) = outer_of(Some(a)) {
out.push_str(ON);
out.push_str(outer);
}
out
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum Leaf {
Text {
text: String,
marks: Marks,
link: Option<String>,
},
Raw(String),
Comment(Note),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Note {
pub(crate) prose: String,
pub(crate) code: String,
}
impl Note {
#[cfg(test)]
pub(crate) fn same(text: &str) -> Self {
Self {
prose: text.to_string(),
code: text.to_string(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum Token {
Leaf(Leaf),
Open(Mark, Option<String>),
Close(Mark),
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum Node {
Leaf(Leaf),
Span(Mark, Option<String>, Vec<Node>),
Split(Mark, Option<String>, Vec<Node>),
}
impl Node {
fn has_content(&self) -> bool {
match self {
Self::Leaf(Leaf::Comment(_)) => false,
Self::Leaf(_) => true,
Self::Span(_, _, children) | Self::Split(.., children) => {
children.iter().any(Self::has_content)
}
}
}
}
#[derive(Debug, Default)]
pub(crate) struct Critic {
tokens: Vec<Token>,
inline_end: bool,
agent: bool,
code_block: bool,
source_dates: std::collections::HashMap<String, Option<String>>,
}
impl Critic {
pub(crate) fn set_agent(&mut self) {
self.agent = true;
}
pub(crate) fn set_code_block(&mut self) {
self.code_block = true;
}
pub(crate) fn set_inline_end(&mut self) {
self.inline_end = true;
}
pub(crate) fn push(&mut self, text: &str, bold: bool, italic: bool, link: Option<&str>) {
let marks = Marks {
bold,
italic,
..Marks::default()
};
self.push_styled(text, marks, link);
}
pub(crate) fn push_styled(&mut self, text: &str, marks: Marks, link: Option<&str>) {
if !text.is_empty() {
self.tokens.push(Token::Leaf(Leaf::Text {
text: text.to_string(),
marks,
link: link.map(str::to_string),
}));
}
}
pub(crate) fn raw(&mut self, markdown: &str) {
if !markdown.is_empty() {
self.tokens
.push(Token::Leaf(Leaf::Raw(markdown.to_string())));
}
}
pub(crate) fn insert_raw(&mut self, at: usize, markdown: &str) {
for token in &mut self.tokens[at..] {
match token {
Token::Leaf(Leaf::Text { text, .. }) => {
let trimmed = text.trim_start().to_string();
let done = !trimmed.is_empty();
*text = trimmed;
if done {
break;
}
}
_ => break,
}
}
self.tokens
.insert(at, Token::Leaf(Leaf::Raw(markdown.to_string())));
}
pub(crate) fn reopen(&mut self, markdown: &str) -> bool {
let last =
matches!(self.tokens.last(), Some(Token::Leaf(Leaf::Raw(raw))) if raw == markdown);
if last {
self.tokens.pop();
}
last
}
pub(crate) fn len(&self) -> usize {
self.tokens.len()
}
pub(crate) fn truncate(&mut self, len: usize) {
self.tokens.truncate(len);
}
pub(crate) fn comment(&mut self, note: &Note) {
self.tokens.push(Token::Leaf(Leaf::Comment(note.clone())));
}
pub(crate) fn open(&mut self, mark: Mark, by: Option<&str>) {
self.tokens.push(Token::Open(mark, by.map(str::to_string)));
}
pub(crate) fn open_dated(&mut self, mark: Mark, by: Option<&str>, date: Option<String>) {
if let Some(by) = by {
self.source_dates.insert(by.to_string(), date);
}
self.open(mark, by);
}
pub(crate) fn close(&mut self, mark: Mark) {
self.tokens.push(Token::Close(mark));
}
pub(crate) fn unattributed(mut self) -> Self {
for token in &mut self.tokens {
if let Token::Open(_, by) = token {
*by = None;
}
}
self
}
pub(crate) fn is_blank(&self) -> bool {
let mut changed = 0usize;
self.tokens.iter().all(|token| match token {
Token::Leaf(Leaf::Text { text, marks, .. }) => {
let marked = marks.underline || marks.highlight.is_some() || marks.strike;
let spaces = !text.is_empty() && text.chars().all(|c| c == ' ');
let visible = !text.trim().is_empty() || (spaces && marked);
changed == 0 && !visible
}
Token::Leaf(Leaf::Raw(text)) => changed == 0 && text.trim().is_empty(),
Token::Leaf(Leaf::Comment(_)) => false,
Token::Open(Mark::Insertion | Mark::Deletion, _) => {
changed += 1;
true
}
Token::Close(Mark::Insertion | Mark::Deletion) => {
changed = changed.saturating_sub(1);
true
}
Token::Open(..) | Token::Close(_) => true,
})
}
pub(crate) fn into_story(self) -> String {
let nodes = tidy(unnest(tree(self.tokens)));
let mut pieces = Vec::new();
render(
&nodes,
&mut pieces,
Escaping {
code_block: false,
story: true,
source_dates: &self.source_dates,
},
&mut 0,
);
pieces.into_iter().map(|piece| piece.text).collect()
}
pub(crate) fn into_inline(self) -> Inline {
let mut nodes = tidy(unnest(tree(self.tokens)));
if self.inline_end {
space_into_last_change(&mut nodes);
}
let escaping = Escaping {
code_block: self.code_block,
story: false,
source_dates: &self.source_dates,
};
let mut pieces = Vec::new();
render(&nodes, &mut pieces, escaping, &mut 0);
wrap_markers(&mut pieces);
let mut inline = Inline::default();
if self.code_block {
inline.verbatim();
} else if self.agent {
inline.keep_spaces();
}
for piece in pieces {
inline.push_styled(&piece.text, piece.marks, piece.link.as_deref());
}
inline
}
}
type Open = (Mark, Option<String>, Vec<Node>);
fn same_change_note(outer: Option<&str>, inner: Option<&str>) -> bool {
match (outer, inner) {
(None, None) => true,
(Some(a), Some(b)) if a == b => true,
(Some(a), Some(b)) => match (tag(Some(a)), tag(Some(b))) {
(Some(left), Some(right)) => {
let (left, right) = (tag_parts(left).0, tag_parts(right).0);
super::agent::same_change(left, right) || same_handle(left, right)
}
_ => false,
},
_ => false,
}
}
fn same_handle(left: &str, right: &str) -> bool {
match (
super::agent::handle_of(left),
super::agent::handle_of(right),
) {
(Some(outer), Some(inner)) if outer != "??" => outer == inner,
_ => false,
}
}
fn substitution_side(children: &[Node], mark: Mark, by: &Option<String>, rest: &[Token]) -> bool {
match mark {
Mark::Insertion => {
last_deletion(children).is_some_and(|old| pairs(old.as_deref(), by.as_deref()))
}
Mark::Deletion => {
following_insertion(rest).is_some_and(|new| pairs(by.as_deref(), new.as_deref()))
}
_ => false,
}
}
fn last_deletion(children: &[Node]) -> Option<&Option<String>> {
let mut rest = children;
loop {
match rest.split_last() {
Some((Node::Leaf(Leaf::Text { text, .. }), head)) if text.is_empty() => rest = head,
Some((Node::Leaf(Leaf::Comment(_)), head)) => rest = head,
_ => break,
}
}
match rest.last() {
Some(Node::Span(Mark::Deletion, by, _)) => Some(by),
_ => None,
}
}
fn following_insertion(rest: &[Token]) -> Option<&Option<String>> {
let mut depth = 1i32;
let mut closed = false;
for token in rest {
if !closed {
match token {
Token::Open(Mark::Insertion | Mark::Deletion, _) => depth += 1,
Token::Close(Mark::Insertion | Mark::Deletion) => {
depth -= 1;
if depth == 0 {
closed = true;
}
}
_ => {}
}
continue;
}
match token {
Token::Open(Mark::Insertion, by) => return Some(by),
Token::Close(_) => {}
Token::Leaf(Leaf::Text { text, .. }) if text.is_empty() => {}
Token::Leaf(Leaf::Comment(_)) => {}
_ => return None,
}
}
None
}
fn pairs(old_by: Option<&str>, new_by: Option<&str>) -> bool {
same_nest(old_by, new_by)
&& !holds(new_by, old_by)
&& one_change(old_by, new_by)
&& pairable_attribution(old_by, new_by)
}
fn merges(
outer_by: Option<&str>,
children: &[Node],
mark: Mark,
by: &Option<String>,
rest: &[Token],
) -> bool {
same_change_note(outer_by, by.as_deref()) || !substitution_side(children, mark, by, rest)
}
fn tree(tokens: Vec<Token>) -> Vec<Node> {
let mut root = Vec::new();
let mut open: Vec<Open> = Vec::new();
let mut merged = [0usize; 3];
let mut tokens = tokens.into_iter();
while let Some(token) = tokens.next() {
match token {
Token::Leaf(leaf) => children(&mut root, &mut open).push(Node::Leaf(leaf)),
Token::Open(mark, by) => {
let merges_into = open
.iter()
.rposition(|(m, ..)| *m == mark)
.is_some_and(|at| {
open[at + 1..]
.iter()
.all(|(m, ..)| matches!(m, Mark::Scope))
&& merges(
open[at].1.as_deref(),
&open[at].2,
mark,
&by,
tokens.as_slice(),
)
});
if merges_into {
merged[mark.index()] += 1;
} else {
open.push((mark, by, Vec::new()));
}
}
Token::Close(mark) if merged[mark.index()] > 0 => merged[mark.index()] -= 1,
Token::Close(mark) => {
if let Some(at) = open.iter().rposition(|(m, ..)| *m == mark) {
let reopen: Vec<(Mark, Option<String>)> = open[at + 1..]
.iter()
.map(|(m, by, _)| (*m, by.clone()))
.collect();
close_from(&mut root, &mut open, at);
open.extend(reopen.into_iter().map(|(m, by)| (m, by, Vec::new())));
}
}
}
}
close_from(&mut root, &mut open, 0);
root
}
fn children<'a>(root: &'a mut Vec<Node>, open: &'a mut [Open]) -> &'a mut Vec<Node> {
match open.last_mut() {
Some((_, _, nodes)) => nodes,
None => root,
}
}
fn close_from(root: &mut Vec<Node>, open: &mut Vec<Open>, at: usize) {
let closed = open.split_off(at);
let outermost = closed
.into_iter()
.rev()
.fold(None, |inner, (mark, by, mut nodes)| {
nodes.extend(inner);
Some(Node::Span(mark, by, nodes))
});
children(root, open).extend(outermost);
}
fn is_change(node: &Node) -> bool {
match node {
Node::Split(..) => true,
Node::Span(Mark::Scope, _, children) => children.iter().any(is_change),
Node::Span(..) => true,
_ => false,
}
}
fn held_change(piece: &Node, outer_mark: Mark, outer_by: Option<&str>) -> bool {
match piece {
Node::Split(..) => true,
Node::Span(Mark::Scope, _, children) => children.iter().any(is_change),
Node::Span(mark, by, _) => {
outer_of(by.as_deref()).is_some()
|| *mark != outer_mark
|| !same_change_note(outer_by, by.as_deref())
}
_ => false,
}
}
fn unnest(nodes: Vec<Node>) -> Vec<Node> {
fn pieces(mark: Mark, by: &Option<String>, children: Vec<Node>) -> Vec<Node> {
let mut out = Vec::new();
let mut live = Vec::new();
for child in children {
if is_change(&child) {
if !live.is_empty() {
out.push(Node::Span(mark, by.clone(), std::mem::take(&mut live)));
}
out.push(match child {
Node::Span(Mark::Scope, note, children) => {
Node::Span(Mark::Scope, note, pieces(mark, by, children))
}
child => child,
});
} else {
live.push(child);
}
}
if !live.is_empty() {
out.push(Node::Span(mark, by.clone(), live));
}
out
}
nodes
.into_iter()
.map(|node| {
let Node::Span(mark, by, children) = node else {
return node;
};
let children = unnest(children);
if matches!(mark, Mark::Insertion | Mark::Deletion) && children.iter().any(is_change) {
Node::Split(mark, by.clone(), pieces(mark, &by, children))
} else {
Node::Span(mark, by, children)
}
})
.collect()
}
fn fold_on(node: &mut Node, outer: Option<&str>) {
let Some(outer) = outer else {
return;
};
if outer.ends_with(CARRIED) {
return;
}
let Some(tagged) = outer
.strip_prefix(TAG)
.or_else(|| outer.strip_prefix(PLAIN))
else {
return;
};
match node {
Node::Span(Mark::Insertion | Mark::Deletion, by, _) => {
if let Some(own) = by.as_ref()
&& sentinel(own) == sentinel(outer)
&& tag(Some(own)) != tag(Some(outer))
{
*by = Some(format!("{own}{ON}{tagged}"));
}
}
Node::Span(Mark::Scope, _, children) | Node::Split(_, _, children) => {
for child in children {
fold_on(child, Some(outer));
}
}
_ => {}
}
}
fn tidy(nodes: Vec<Node>) -> Vec<Node> {
let mut out: Vec<Node> = Vec::new();
for node in nodes {
let mut comments = Vec::new();
let node = if let Node::Split(mark, outer, pieces) = node {
let mut pieces = tidy(pieces);
pieces.retain(|piece| {
if piece.has_content() {
true
} else {
lift_comments(std::slice::from_ref(piece).to_vec(), &mut comments);
false
}
});
if pieces.is_empty() {
out.extend(comments);
continue;
}
for piece in &mut pieces {
if held_change(piece, mark, outer.as_deref()) {
fold_on(piece, outer.as_deref());
}
}
if pieces.len() == 1 {
pieces.remove(0)
} else {
out.push(Node::Split(mark, outer, pieces));
out.extend(comments);
continue;
}
} else {
node
};
let Node::Span(mark, by, nodes) = node else {
out.push(node);
out.extend(comments);
continue;
};
let nodes = if mark == Mark::Scope {
lift_comments(nodes, &mut comments)
} else {
nodes
};
if !nodes.iter().any(Node::has_content) {
lift_comments(nodes, &mut out);
} else if let Some(Node::Span(_, _, before)) = out
.last_mut()
.filter(|last| matches!(last, Node::Span(m, b, _) if *m == mark && b == &by && (mark == Mark::Scope || tag(b.as_deref()).is_none())))
{
before.extend(nodes);
} else {
out.push(Node::Span(mark, by, nodes));
}
out.extend(comments);
}
join_text(
out.into_iter()
.map(|node| match node {
Node::Span(mark, by, nodes) => Node::Span(mark, by, tidy(nodes)),
leaf => leaf,
})
.collect(),
)
}
fn join_text(nodes: Vec<Node>) -> Vec<Node> {
let mut out: Vec<Node> = Vec::with_capacity(nodes.len());
for node in nodes {
match (out.last_mut(), node) {
(
Some(Node::Leaf(Leaf::Text {
text: before,
marks: m,
link: l,
})),
Node::Leaf(Leaf::Text { text, marks, link }),
) if *m == marks && *l == link => {
before.push_str(&text);
}
(_, node) => out.push(node),
}
}
out
}
fn space_into_last_change(nodes: &mut [Node]) {
let [
..,
Node::Leaf(Leaf::Text { text, .. }),
Node::Span(Mark::Insertion | Mark::Deletion, by, inner),
] = nodes
else {
return;
};
if by.as_deref().is_some_and(|by| by.starts_with(TAG)) {
return;
}
let Some(Node::Leaf(Leaf::Text { text: first, .. })) = inner.first_mut() else {
return;
};
let kept = text.trim_end().len();
if kept == text.len() || kept == 0 {
return;
}
first.insert_str(0, &text[kept..]);
text.truncate(kept);
}
fn lift_comments(nodes: Vec<Node>, comments: &mut Vec<Node>) -> Vec<Node> {
let mut kept = Vec::new();
for node in nodes {
match node {
Node::Leaf(Leaf::Comment(_)) => comments.push(node),
Node::Span(mark, by, nodes) => {
kept.push(Node::Span(mark, by, lift_comments(nodes, comments)));
}
Node::Split(mark, outer, pieces) => {
kept.push(Node::Split(mark, outer, lift_comments(pieces, comments)));
}
leaf => kept.push(leaf),
}
}
kept
}
struct Piece {
text: String,
marks: Marks,
link: Option<String>,
marker: Option<usize>,
}
#[derive(Clone, Copy)]
struct Escaping<'a> {
code_block: bool,
story: bool,
source_dates: &'a std::collections::HashMap<String, Option<String>>,
}
impl Escaping<'_> {
fn pairable(self, a: Option<&str>, b: Option<&str>) -> bool {
let date = |by: Option<&str>| {
by.and_then(|by| {
self.source_dates
.get(bare(by).split(ON).next().unwrap_or_default())
})
};
pairable_attribution(a, b)
&& match (date(a), date(b)) {
(Some(a), Some(b)) => a == b,
_ => true,
}
}
fn text(self, text: &str, marks: Marks) -> String {
if self.code_block {
escape_code(text)
} else if marks.code {
text.to_string()
} else {
escape(&super::agent::escape_markdown(text))
}
}
}
fn render(nodes: &[Node], out: &mut Vec<Piece>, escaping: Escaping<'_>, ids: &mut usize) {
fn flatten(nodes: &[Node], out: &mut Vec<Node>) {
for node in nodes {
if let Node::Split(.., pieces) = node {
flatten(pieces, out);
} else {
out.push(node.clone());
}
}
}
let mut flat = Vec::new();
flatten(nodes, &mut flat);
let nodes = flat.as_slice();
let mut index = 0;
while index < nodes.len() {
match (&nodes[index], nodes.get(index + 1)) {
(
Node::Span(Mark::Deletion, old_by, old),
Some(Node::Span(Mark::Insertion, new_by, new)),
) if same_nest(old_by.as_deref(), new_by.as_deref())
&& !holds(new_by.as_deref(), old_by.as_deref())
&& one_change(old_by.as_deref(), new_by.as_deref())
&& escaping.pairable(old_by.as_deref(), new_by.as_deref())
&& new.iter().any(Node::has_content) =>
{
*ids += 1;
let id = *ids;
marker(out, "{~~", id);
render(old, out, escaping, ids);
marker(out, "~>", id);
render(new, out, escaping, ids);
marker(out, "~~}", id);
match (old_by.as_deref(), new_by.as_deref()) {
(Some(a), Some(b))
if tag(Some(a)).is_some()
&& escaping.pairable(old_by.as_deref(), new_by.as_deref()) =>
{
let joined = join_tagged(a, b);
attribution(out, Some(&joined), id);
}
_ => {
attribution(out, old_by.as_deref(), id);
if new_by != old_by {
attribution(out, new_by.as_deref(), id);
}
}
}
index += 2;
continue;
}
(Node::Span(mark, by, nodes), _) => {
*ids += 1;
let id = *ids;
let (open, close) = mark.delimiters();
marker(out, open, id);
render(nodes, out, escaping, ids);
marker(out, close, id);
attribution(out, by.as_deref(), id);
}
(Node::Split(.., pieces), _) => {
for piece in pieces {
render(std::slice::from_ref(piece), out, escaping, ids);
}
}
(Node::Leaf(Leaf::Text { text, marks, link }), _) => {
out.push(Piece {
text: escaping.text(text, *marks),
marks: *marks,
link: link.clone(),
marker: None,
});
}
(Node::Leaf(Leaf::Raw(markdown)), _) => out.push(Piece {
text: if escaping.story {
markdown.clone()
} else {
math_changes(&if escaping.code_block {
escape_code(markdown)
} else {
defuse(markdown)
})
},
marks: Marks::default(),
link: None,
marker: None,
}),
(Node::Leaf(Leaf::Comment(comment)), _) => {
*ids += 1;
let inner = if escaping.code_block {
&comment.code
} else {
&comment.prose
};
marker(out, ¬e(inner), *ids);
}
}
index += 1;
}
}
fn marker(out: &mut Vec<Piece>, text: &str, id: usize) {
out.push(Piece {
text: text.to_string(),
marks: Marks::default(),
link: None,
marker: Some(id),
});
}
fn wrap_markers(pieces: &mut [Piece]) {
type Format = (Marks, Option<String>);
let format = |piece: &Piece| -> Format {
let marks = if piece.marks.code {
Marks::default()
} else {
piece.marks
};
(marks, piece.link.clone())
};
let mut joined: Vec<Option<Format>> = vec![None; pieces.len()];
let mut start = 0;
while start < pieces.len() {
if pieces[start].marker.is_none() {
start += 1;
continue;
}
let end = (start..pieces.len())
.find(|&at| pieces[at].marker.is_none())
.unwrap_or(pieces.len());
let before = start.checked_sub(1).map(|at| format(&pieces[at]));
let after = pieces.get(end).map(format);
if let Some(around) =
before.filter(|f| *f != (Marks::default(), None) && Some(f) == after.as_ref())
{
joined[start..end].fill(Some(around));
}
start = end;
}
let mut refused: std::collections::HashSet<usize> = pieces
.iter()
.zip(&joined)
.filter(|(piece, around)| around.is_none() && piece.marker.is_some())
.filter_map(|(piece, _)| piece.marker)
.collect();
loop {
let mut more = false;
let mut start = 0;
while start < pieces.len() {
let end = (start..pieces.len())
.find(|&at| pieces[at].marker.is_none())
.unwrap_or(pieces.len());
let run = || pieces[start..end].iter().filter_map(|piece| piece.marker);
if run().any(|id| refused.contains(&id)) {
for id in run() {
more |= refused.insert(id);
}
}
start = end + 1;
}
if !more {
break;
}
}
for (piece, around) in pieces.iter_mut().zip(joined) {
if let Some((marks, link)) =
around.filter(|_| piece.marker.is_some_and(|id| !refused.contains(&id)))
{
piece.marks = marks;
piece.link = link;
}
}
}
fn attribution(out: &mut Vec<Piece>, by: Option<&str>, id: usize) {
if let Some(by) = by {
marker(out, &attribution_note(&display(by)), id);
}
}
pub(super) fn attribution_note(inner: &str) -> String {
let mut out = String::from("{");
let mut escaped = false;
for c in inner.chars() {
if matches!(c, '{' | '}') && !escaped {
out.push('\\');
}
out.push(c);
escaped = c == '\\' && !escaped;
}
out.push('}');
out
}
fn note(inner: &str) -> String {
format!("{{>>{inner}<<}}")
}
pub(crate) fn escape(text: &str) -> String {
const DELIMITERS: [(&str, &str); 11] = [
("{++", "{\\++"),
("{--", "{\\--"),
("{~~", "{\\~~"),
("{>>", "{\\>>"),
("{==", "{\\=="),
("++}", "++\\}"),
("--}", "--\\}"),
("~~}", "~~\\}"),
("<<}", "<<\\}"),
("==}", "==\\}"),
("~>", "~\\>"),
];
if !text.contains(['{', '}', '~']) {
return text.to_string();
}
let text = DELIMITERS
.iter()
.fold(text.to_string(), |text, (from, to)| text.replace(from, to));
let mut out = String::new();
for (at, c) in text.char_indices() {
if c == '{' && crate::markdown::critic::attribution_tag(&text[at..]).is_some() {
out.push('\\');
}
out.push(c);
}
out
}
pub(crate) fn escape_code(text: &str) -> String {
const OPENER: [&str; 5] = ["++", "--", "~~", ">>", "=="];
const CLOSER: [&str; 5] = ["++", "--", "~~", "<<", "=="];
let bytes = text.as_bytes();
let shape = |at: usize| -> Option<(usize, usize, usize)> {
let shape = |head: usize, tails: &[&str]| {
let mut run = at + head;
while bytes.get(run) == Some(&b'\\') {
run += 1;
}
let tail = tails
.iter()
.find(|tail| text[run..].starts_with(*tail))?
.len();
Some((head, run - (at + head), tail))
};
if bytes.get(at) == Some(&b'{') {
shape(1, &OPENER)
} else if CLOSER.iter().any(|head| text[at..].starts_with(head)) {
shape(2, &["}"])
} else if bytes.get(at) == Some(&b'~') {
shape(1, &[">"])
} else {
None
}
};
let mut out = String::with_capacity(text.len());
let mut at = 0;
while at < text.len() {
let mut tag_at = at;
while bytes.get(tag_at) == Some(&b'\\') {
tag_at += 1;
}
if let Some((_, width)) = crate::markdown::critic::attribution_tag(&text[tag_at..]) {
out.push_str(&"\\".repeat((tag_at - at) * 2 + 1));
out.push_str(&text[tag_at..tag_at + width]);
at = tag_at + width;
continue;
}
if let Some((head, run, tail)) = shape(at) {
out.push_str(&text[at..at + head]);
for _ in 0..run * 2 + 1 {
out.push('\\');
}
out.push_str(&text[at + head + run..at + head + run + tail]);
at += head + run + tail;
} else {
let c = text[at..].chars().next().unwrap_or_default();
out.push(c);
at += c.len_utf8();
}
}
out
}
fn defuse(markdown: &str) -> String {
const SPACED: [(&str, &str); 11] = [
("{++", "{ ++"),
("{--", "{ --"),
("{~~", "{ ~~"),
("{>>", "{ >>"),
("{==", "{ =="),
("++}", "++ }"),
("--}", "-- }"),
("~~}", "~~ }"),
("<<}", "<< }"),
("==}", "== }"),
("~>", "~ >"),
];
const GROUPED: [(&str, &str); 11] = [
("{++", "{{}++"),
("{--", "{{}--"),
("{~~", "{{}~~"),
("{>>", "{{}>>"),
("{==", "{{}=="),
("++}", "++{}}"),
("--}", "--{}}"),
("~~}", "~~{}}"),
("<<}", "<<{}}"),
("==}", "=={}}"),
("~>", "~{}>"),
];
let mut out = String::with_capacity(markdown.len());
let mut rest = markdown;
while !rest.is_empty() {
let Some(start) = super::unescaped_dollar(rest) else {
out.push_str(&break_delimiters(rest, &SPACED));
break;
};
out.push_str(&break_delimiters(&rest[..start], &SPACED));
let fence = if rest[start..].starts_with("$$") {
"$$"
} else {
"$"
};
let body = start + fence.len();
let Some(len) = super::math_body(&rest[body..], fence) else {
out.push_str(&break_delimiters(&rest[start..], &SPACED));
break;
};
let end = body + len + fence.len();
out.push_str(fence);
out.push_str(&break_delimiters(&rest[body..body + len], &GROUPED));
out.push_str(fence);
rest = &rest[end..];
}
out
}
fn break_delimiters(text: &str, marks: &[(&str, &str)]) -> String {
marks
.iter()
.fold(text.to_string(), |text, (from, to)| text.replace(from, to))
}
fn math_changes(markdown: &str) -> String {
use crate::markdown::math;
if !markdown.contains([
math::INSERT_START,
math::INSERT_END,
math::DELETE_START,
math::DELETE_END,
]) {
return markdown.to_string();
}
markdown
.replace(math::INSERT_START, "{++")
.replace(math::INSERT_END, "++}")
.replace(math::DELETE_START, "{--")
.replace(math::DELETE_END, "--}")
}
fn ends_with_fence(out: &str) -> bool {
out.lines().next_back().is_some_and(|line| {
let line = line.trim();
line.len() >= 3 && line.bytes().all(|b| b == b'`')
})
}
pub(crate) fn splice(
out: &mut String,
separator: &str,
prefix: &str,
body: &str,
change: Option<&Change>,
space: bool,
) {
let Some((mark, by)) = change else {
out.push_str(separator);
out.push_str(prefix);
out.push_str(body);
return;
};
let (open, close) = mark.delimiters();
let shown = by.as_deref().map(display);
let by = shown.as_deref().map(attribution_note).unwrap_or_default();
let end = format!("{close}{by}");
let continues = body.strip_prefix(open).filter(|rest| {
rest.find(close)
.is_some_and(|at| rest[at + close.len()..].starts_with(&by))
});
let fence = ends_with_fence(out);
if let Some(kept) = out.strip_suffix(&end) {
out.truncate(kept.len());
} else if fence {
out.push_str(separator);
out.push_str(prefix);
if let Some(rest) = continues {
out.push_str(open);
out.push_str(rest);
} else {
out.push_str(body);
}
return;
} else {
out.push_str(open);
}
out.push_str(separator);
out.push_str(prefix);
if let Some(rest) = continues {
out.push_str(rest);
} else {
out.push_str(&end);
if space {
out.push(' ');
}
out.push_str(body);
}
}
pub(crate) fn whole_change(part: &str) -> Option<Change> {
[Mark::Insertion, Mark::Deletion]
.into_iter()
.find_map(|mark| {
let (open, close) = mark.delimiters();
let inner = part.strip_prefix(open)?;
let after = &inner[inner.find(close)? + close.len()..];
match after {
"" => Some((mark, None)),
_ => {
let (by, width) = crate::markdown::critic::attribution_tag(after)?;
(width == after.len()).then(|| (mark, Some(by.to_string())))
}
}
})
}
pub(crate) fn join_changed(parts: Vec<String>, separator: &str) -> String {
let mut parts = parts.into_iter();
let mut out = parts.next().unwrap_or_default();
let first = whole_change(&out);
for (index, part) in parts.enumerate() {
let change = whole_change(&part).or_else(|| first.clone().filter(|_| index == 0));
splice(&mut out, separator, "", &part, change.as_ref(), false);
}
out
}
pub(crate) type Part = (String, Option<Change>, (bool, bool));
pub(crate) fn join_marked(parts: Vec<Part>, separator: &str) -> String {
join_paragraphs(parts, separator, false)
}
pub(crate) fn join_paragraphs(parts: Vec<Part>, separator: &str, keep_empty: bool) -> String {
let mut out = String::new();
let mut pending = None;
let mut trailing = false;
let mut first = None;
for (i, (part, mark, (leading, ends_in_space))) in parts.into_iter().enumerate() {
if part.trim().is_empty() {
pending = if keep_empty { mark } else { None };
if keep_empty && i > 0 {
first = None;
out.push_str(separator);
}
continue;
}
if out.is_empty() {
first = whole_change(&part);
if keep_empty && i > 0 {
out.push_str(separator);
}
out.push_str(&part);
} else {
let first = first.take();
let change = if keep_empty {
pending.take()
} else {
pending.take().or_else(|| whole_change(&part)).or(first)
};
let space = trailing || (leading && !part.starts_with(" "));
splice(&mut out, separator, "", &part, change.as_ref(), space);
}
pending = mark;
trailing = ends_in_space;
}
out
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod tests {
use super::*;
use Mark::{Deletion as Del, Insertion as Ins, Scope as Sc};
fn text(critic: &mut Critic, t: &str) {
critic.push(t, false, false, None);
}
fn md(critic: Critic) -> String {
critic.into_inline().render(true)
}
fn script(steps: &[(&str, &str)]) -> String {
let mut critic = Critic::default();
for (op, value) in steps {
match *op {
"open" => critic.open(kind(value), None),
op if op.starts_with("by") => critic.open(kind(&op[2..]), Some(value)),
"close" => critic.close(kind(value)),
"note" => critic.comment(&Note::same(value)),
"raw" => critic.raw(value),
_ => text(&mut critic, value),
}
}
md(critic)
}
fn kind(value: &str) -> Mark {
match value {
"+" => Ins,
"-" => Del,
_ => Sc,
}
}
#[test]
fn plain_marks_render_with_their_delimiters() {
assert_eq!(
script(&[
("open", "+"),
("t", "a"),
("close", "+"),
("t", " "),
("open", "="),
("t", "b"),
("close", "=")
]),
"{++a++} {==b==}"
);
assert_eq!(
script(&[("open", "-"), ("t", "gone"), ("close", "-")]),
"{--gone--}"
);
}
#[test]
fn a_deletion_then_an_insertion_is_a_substitution_and_the_reverse_two_changes() {
let del_ins = [
("open", "-"),
("t", "old"),
("close", "-"),
("open", "+"),
("t", "new"),
("close", "+"),
];
let ins_del = [
("open", "+"),
("t", "new"),
("close", "+"),
("open", "-"),
("t", "old"),
("close", "-"),
];
assert_eq!(script(&ins_del), "{++new++}{--old--}");
assert_eq!(script(&del_ins), "{~~old~>new~~}");
let triple = [
("open", "-"),
("t", "a"),
("close", "-"),
("open", "+"),
("t", "b"),
("close", "+"),
("open", "-"),
("t", "c"),
("close", "-"),
];
assert_eq!(script(&triple), "{~~a~>b~~}{--c--}");
}
#[test]
fn another_authors_substitution_stays_inside_the_same_kind() {
let inside_insertion = [
("by+", "\u{E000}7+8@B"),
("t", "x"),
("by-", "\u{E000}3+4@A"),
("t", "a"),
("close", "-"),
("by+", "\u{E000}3+4@A"),
("t", "b"),
("close", "+"),
("t", "y"),
("close", "+"),
];
let inside_deletion = [
("by-", "\u{E000}7+8@B"),
("t", "x"),
("by-", "\u{E000}3+4@A"),
("t", "a"),
("close", "-"),
("by+", "\u{E000}3+4@A"),
("t", "b"),
("close", "+"),
("t", "y"),
("close", "-"),
];
assert_eq!(
script(&inside_insertion),
"{++x++}{r7+8 @B}{~~a~>b~~}{r3+4+3+4 @A re r7+8 @B}{++y++}{r7+8 @B}"
);
assert_eq!(
script(&inside_deletion),
"{--x--}{r7+8 @B}{~~a~>b~~}{r3+4+3+4 @A re r7+8 @B}{--y--}{r7+8 @B}"
);
}
#[test]
fn same_kind_nesting_is_merged_into_one_span() {
let nested = [
("open", "-"),
("t", "a"),
("open", "-"),
("t", "b"),
("close", "-"),
("t", "c"),
("close", "-"),
("t", "d"),
];
assert_eq!(script(&nested), "{--abc--}d");
}
#[test]
fn merged_spans_are_counted_per_kind() {
let steps = [
("open", "="),
("open", "="),
("t", "a"),
("open", "+"),
("t", "b"),
("close", "+"),
("t", "c"),
("close", "="),
("close", "="),
];
assert_eq!(script(&steps), "{==a{++b++}c==}");
}
#[test]
fn different_kinds_cannot_nest() {
let nested = [
("open", "+"),
("open", "-"),
("t", "x"),
("close", "-"),
("close", "+"),
];
assert_eq!(script(&nested), "{--x--}");
}
#[test]
fn a_change_inside_a_change_splits_the_outer_one() {
let nested = [
("by+", "Ana"),
("t", "one "),
("by-", "Ben"),
("t", "two"),
("close", "-"),
("t", " three"),
("close", "+"),
];
assert_eq!(
script(&nested),
"{++one ++}{Ana}{--two--}{Ben}{++ three++}{Ana}"
);
}
#[test]
fn a_change_that_is_another_s_only_content_names_it_in_the_note() {
let nested = [
("by+", "\u{E000}1@AL"),
("by-", "\u{E000}3@BO"),
("t", "x"),
("close", "-"),
("close", "+"),
];
assert_eq!(script(&nested), "{--x--}{r3 @BO re r1 @AL}");
let dated = [
("by+", "\u{E000}1@AL 2026-01-01T09:00:00Z"),
("by-", "\u{E000}3@BO 2026-01-02T10:00:00Z"),
("t", "x"),
("close", "-"),
("close", "+"),
];
assert_eq!(
script(&dated),
"{--x--}{r3 @BO 2026-01-02T10:00:00Z re r1 @AL 2026-01-01T09:00:00Z}"
);
let plain = [
("by+", "\u{E001}1@Ana%20Lima%20(2026-01-01T09:00:00Z)"),
("by-", "\u{E001}3@Ben%20Ode%20(2026-01-02T10:00:00Z)"),
("t", "x"),
("close", "-"),
("close", "+"),
];
assert_eq!(
script(&plain),
"{--x--}{r3 Ben Ode (2026-01-02T10:00:00Z) \
re r1 Ana Lima (2026-01-01T09:00:00Z)}"
);
}
#[test]
fn a_note_that_names_no_change_keeps_the_sole_one() {
let nested = [
("by+", "Ana"),
("by-", "Ben"),
("t", "x"),
("close", "-"),
("close", "+"),
];
assert_eq!(script(&nested), "{--x--}{Ben}");
}
#[test]
fn an_insertion_inside_a_deletion_splits_it_too() {
let nested = [
("by-", "Ben"),
("t", "one "),
("by+", "Ana"),
("t", "two"),
("close", "+"),
("t", " three"),
("close", "-"),
];
assert_eq!(
script(&nested),
"{--one --}{Ben}{++two++}{Ana}{-- three--}{Ben}"
);
}
#[test]
fn split_pieces_do_not_pair_as_a_substitution() {
let nested = [
("by+", "Ana"),
("t", "one "),
("by-", "Ben"),
("t", "two"),
("close", "-"),
("t", " three"),
("close", "+"),
("by-", "Ben"),
("t", "four"),
("close", "-"),
];
assert_eq!(
script(&nested),
"{++one ++}{Ana}{--two--}{Ben}{++ three++}{Ana}\
{--four--}{Ben}"
);
}
#[test]
fn a_nest_inside_a_nest_splits_at_every_level() {
let nested = [
("by+", "Ana"),
("t", "a"),
("by-", "Ben"),
("t", "x"),
("close", "-"),
("t", "y"),
("by-", "Cid"),
("t", "z"),
("close", "-"),
("t", "b"),
("close", "+"),
];
assert_eq!(
script(&nested),
"{++a++}{Ana}{--x--}{Ben}{++y++}{Ana}{--z--}{Cid}{++b++}{Ana}"
);
}
#[test]
fn crossing_spans_are_split_so_each_closes_inside_its_parent() {
let crossing = [
("open", "="),
("t", "a"),
("open", "+"),
("t", "b"),
("close", "="),
("t", "c"),
("close", "+"),
];
assert_eq!(script(&crossing), "{==a{++b++}==}{++c++}");
}
#[test]
fn neighbours_of_the_same_kind_join() {
let split = [
("open", "+"),
("t", "a"),
("close", "+"),
("open", "+"),
("t", "b"),
("close", "+"),
];
assert_eq!(script(&split), "{++ab++}");
let deep = [
("open", "-"),
("open", "+"),
("t", "a"),
("close", "+"),
("close", "-"),
("open", "-"),
("open", "+"),
("t", "b"),
("close", "+"),
("close", "-"),
];
assert_eq!(script(&deep), "{++ab++}");
}
#[test]
fn empty_spans_vanish_but_keep_their_comments() {
assert_eq!(
script(&[("t", "a"), ("open", "+"), ("close", "+"), ("t", "b")]),
"ab"
);
assert_eq!(
script(&[
("t", "a"),
("open", "+"),
("open", "-"),
("note", "c"),
("close", "-"),
("close", "+")
]),
"a{>>c<<}"
);
assert_eq!(
script(&[
("t", "a"),
("open", "+"),
("t", " "),
("close", "+"),
("t", "b")
]),
"a{++ ++}b"
);
}
#[test]
fn comments_inside_a_highlight_follow_it() {
let steps = [
("open", "="),
("t", "a"),
("note", "one"),
("open", "+"),
("t", "b"),
("note", "two"),
("close", "+"),
("close", "="),
("t", "."),
];
assert_eq!(script(&steps), "{==a{++b++}==}{>>one<<}{>>two<<}.");
let steps = [
("open", "="),
("t", "a"),
("close", "="),
("note", "x"),
("open", "="),
("t", "b"),
("close", "="),
];
assert_eq!(script(&steps), "{==a==}{>>x<<}{==b==}");
}
#[test]
fn overlapping_highlights_become_their_union() {
let steps = [
("open", "="),
("t", "a"),
("open", "="),
("t", "b"),
("close", "="),
("note", "A"),
("t", "c"),
("close", "="),
("note", "B"),
];
assert_eq!(script(&steps), "{==abc==}{>>A<<}{>>B<<}");
}
#[test]
fn unclosed_spans_close_at_the_end_and_stray_closes_are_ignored() {
assert_eq!(
script(&[("close", "+"), ("open", "-"), ("t", "a")]),
"{--a--}"
);
}
#[test]
fn raw_markdown_is_content_whose_delimiters_are_spaced_apart() {
assert_eq!(
script(&[
("open", "-"),
("raw", "$x_{--}$ {++ ++} ~> {== ==} {>> <<} {~~ ~~}"),
("close", "-"),
("raw", "")
]),
"{--$x_{{}--{}}$ { ++ ++ } ~ > { == == } { >> << } { ~~ ~~ }--}"
);
assert_eq!(defuse("$a+b$"), "$a+b$");
}
#[test]
fn an_equation_breaks_delimiters_on_an_empty_group() {
assert_eq!(defuse("$x_{--}$"), "$x_{{}--{}}$");
assert_eq!(defuse("$y^{++}$"), "$y^{{}++{}}$");
assert_eq!(defuse("$$x_{--}$$"), "$$x_{{}--{}}$$");
assert_eq!(defuse("$a~>$"), "$a~{}>$");
assert_eq!(defuse("$x_{{}--{}}$"), "$x_{{}--{}}$");
assert_eq!(defuse(r"cost \$5 $x_{--}$"), r"cost \$5 $x_{{}--{}}$");
assert_eq!(defuse("cost $5 and {--x--}"), "cost $5 and { --x-- }");
}
#[test]
fn a_tracked_break_finds_the_real_closer_past_an_equation() {
let mut critic = Critic::default();
critic.open(Del, Some("Ana"));
critic.raw("$x_{--}$");
critic.close(Del);
let body = critic.into_inline().render(true);
let mut out = "{--A--}{Ana}".to_string();
splice(
&mut out,
"\n\n",
"",
&body,
Some(&(Del, Some("Ana".into()))),
false,
);
assert_eq!(out, "{--A\n\n$x_{{}--{}}$--}{Ana}");
}
#[test]
fn formatting_and_links_stay_inside_the_markers() {
let mut critic = Critic::default();
critic.open(Ins, None);
critic.push("bold", true, false, None);
critic.close(Ins);
critic.push(" ", false, false, None);
critic.open(Del, None);
critic.push("site", false, false, Some("https://x.test"));
critic.close(Del);
critic.push("", false, false, None);
assert_eq!(md(critic), "{++**bold**++} {--[site](https://x.test)--}");
}
#[test]
fn blankness_counts_changed_text_but_ignores_markers() {
let mut critic = Critic::default();
critic.open(Ins, None);
text(&mut critic, " ");
critic.raw(" ");
critic.close(Ins);
assert!(!critic.is_blank());
let mut scope = Critic::default();
scope.open(Mark::Scope, None);
text(&mut scope, " ");
scope.close(Mark::Scope);
assert!(scope.is_blank());
scope.comment(&Note::same("note"));
assert!(!scope.is_blank());
let mut raw = Critic::default();
raw.raw("");
assert!(!raw.is_blank());
}
#[test]
fn delimiters_in_document_text_are_escaped() {
assert_eq!(escape("plain"), "plain");
assert_eq!(escape("a{b}c"), "a{b}c");
assert_eq!(
escape("{++ {-- {~~ {>> {== ++} --} ~~} <<} ==} ~>"),
"{\\++ {\\-- {\\~~ {\\>> {\\== ++\\} --\\} ~~\\} <<\\} ==\\} ~\\>"
);
assert_eq!(escape("{+++}"), "{\\+++\\}");
assert_eq!(
script(&[("open", "+"), ("t", "a --} b"), ("close", "+")]),
"{++a --\\} b++}"
);
}
#[test]
fn splice_marks_a_tracked_break_and_extends_adjacent_spans() {
let join = |out: &str, body: &str, mark: Option<Mark>| {
let mut out = out.to_string();
splice(
&mut out,
"\n\n",
"",
body,
mark.map(|m| (m, None)).as_ref(),
false,
);
out
};
assert_eq!(join("A", "B", None), "A\n\nB");
assert_eq!(join("A", "B", Some(Del)), "A{--\n\n--}B");
assert_eq!(join("A", "B", Some(Ins)), "A{++\n\n++}B");
assert_eq!(join("{--A--}", "{--B--}", Some(Del)), "{--A\n\nB--}");
assert_eq!(
join("Keep {--old--}", "B", Some(Del)),
"Keep {--old\n\n--}B"
);
assert_eq!(join("A", "{++B++} rest", Some(Ins)), "A{++\n\nB++} rest");
assert_eq!(join("a --\\}", "b", Some(Del)), "a --\\}{--\n\n--}b");
let mut heading = "A".to_string();
splice(&mut heading, "\n\n", "## ", "B", Some(&(Ins, None)), false);
assert_eq!(heading, "A{++\n\n## ++}B");
}
#[test]
fn a_span_after_a_code_fence_opens_on_the_next_block_s_line() {
let join = |out: &str, body: &str, mark: Option<Mark>| {
let mut out = out.to_string();
splice(
&mut out,
"\n\n",
"",
body,
mark.map(|m| (m, None)).as_ref(),
false,
);
out
};
let fence = "```\nsome code\n```";
assert_eq!(
join(fence, "{++B++}", Some(Ins)),
"```\nsome code\n```\n\n{++B++}"
);
assert_eq!(join(fence, "B", Some(Ins)), "```\nsome code\n```\n\nB");
assert_eq!(join(fence, "B", Some(Del)), "```\nsome code\n```\n\nB");
assert_eq!(
join(" ````\ncode\n````", "{++B++}", Some(Ins)),
" ````\ncode\n````\n\n{++B++}"
);
let mut heading = "```\ncode\n```".to_string();
splice(
&mut heading,
"\n\n",
"## ",
"{++B++}",
Some(&(Ins, None)),
false,
);
assert_eq!(heading, "```\ncode\n```\n\n## {++B++}");
assert_eq!(join("A", "B", Some(Ins)), "A{++\n\n++}B");
}
#[test]
fn a_plain_span_across_paragraphs_names_every_piece_s_id() {
let mark = |id: &str| Some(format!("{PLAIN}{id}@Bo%20Chen"));
let join = |out: &str, body: &str, id: &str| {
let mut out = out.to_string();
splice(&mut out, "\n\n", "", body, Some(&(Del, mark(id))), false);
out
};
assert_eq!(
join("a{--A--}{r8 Bo Chen}", "{--B--}{r10 Bo Chen} b", "9"),
"a{--A--}{r8 Bo Chen}{--\n\n--}{r9 Bo Chen}{--B--}{r10 Bo Chen} b"
);
assert_eq!(
join("{--A--}{r8 Bo Chen}", "B", "9"),
"{--A--}{r8 Bo Chen}{--\n\n--}{r9 Bo Chen}B"
);
assert_eq!(
join("A", "{--B--}{r10 Bo Chen}", "9"),
"A{--\n\n--}{r9 Bo Chen}{--B--}{r10 Bo Chen}"
);
let notes = |id: &str| Some(format!("{PLAIN}footnotes#{id}@Bo"));
let mut out = "{--A--}{footnotes.r2 Bo}".to_string();
splice(&mut out, "\n\n", "", "B", Some(&(Del, notes("3"))), false);
assert_eq!(out, "{--A--}{footnotes.r2 Bo}{--\n\n--}{footnotes.r3 Bo}B");
}
#[test]
fn join_marked_uses_each_paragraph_mark_and_resets_on_blanks() {
let bare = (false, false);
let parts = vec![
("a".to_string(), Some((Del, None)), bare),
("b".to_string(), None, bare),
("c".to_string(), Some((Ins, None)), bare),
(" ".to_string(), Some((Del, None)), bare),
("d".to_string(), Some((Del, None)), bare),
];
assert_eq!(join_marked(parts, " "), "a{-- --}b c d");
assert_eq!(join_marked(Vec::new(), " "), "");
}
#[test]
fn a_space_before_a_change_that_ends_the_paragraph_goes_inside_it() {
let joined = |steps: &[(&str, &str)]| {
let mut critic = Critic::default();
critic.set_inline_end();
for (op, value) in steps {
match *op {
"open" => critic.open(kind(value), None),
"close" => critic.close(kind(value)),
_ => text(&mut critic, value),
}
}
md(critic)
};
assert_eq!(
joined(&[("t", "in "), ("open", "+"), ("t", "nested"), ("close", "+")]),
"in{++ nested++}"
);
assert_eq!(
joined(&[("t", "kept "), ("open", "-"), ("t", "gone"), ("close", "-")]),
"kept{-- gone--}"
);
assert_eq!(
joined(&[
("t", "a "),
("open", "+"),
("t", "b"),
("close", "+"),
("t", " c")
]),
"a {++b++} c"
);
assert_eq!(
joined(&[("t", "a "), ("open", "="), ("t", "b"), ("close", "=")]),
"a {==b==}"
);
assert_eq!(
script(&[("t", "in "), ("open", "+"), ("t", "nested"), ("close", "+")]),
"in {++nested++}"
);
}
#[test]
fn a_wholly_changed_paragraph_takes_the_break_before_it() {
let bare = (false, false);
let parts = vec![
("Para".to_string(), None, bare),
("{++Added para++}{noid Alice}".to_string(), None, bare),
];
assert_eq!(
join_marked(parts, "<br>"),
"Para{++<br>Added para++}{noid Alice}"
);
let parts = vec![
("{--Gone--}".to_string(), None, bare),
("Kept".to_string(), None, bare),
];
assert_eq!(join_marked(parts, "<br>"), "{--Gone<br>--}Kept");
}
#[test]
fn a_space_trimmed_at_a_tracked_break_comes_back_after_it() {
let parts = vec![
("notice.".to_string(), Some((Del, None)), (false, false)),
("The".to_string(), None, (true, false)),
("before".to_string(), Some((Ins, None)), (false, true)),
("accepting".to_string(), None, (false, false)),
];
assert_eq!(
join_marked(parts, "<br>"),
"notice.{--<br>--} The<br>before{++<br>++} accepting"
);
let parts = vec![
("a".to_string(), None, (false, true)),
("b".to_string(), None, (true, false)),
];
assert_eq!(join_marked(parts, "<br>"), "a<br>b");
let parts = vec![
("notice.".to_string(), Some((Del, None)), (false, false)),
(" The".to_string(), None, (true, false)),
];
assert_eq!(join_marked(parts, "<br>"), "notice.{--<br>--} The");
}
#[test]
fn each_change_is_followed_by_its_author_and_date() {
let steps = [
("by+", "Ana (2026-01-02T03:04:00Z)"),
("t", "new"),
("close", "+"),
("t", " and "),
("by-", "Bo"),
("t", "old"),
("close", "-"),
("t", "."),
];
assert_eq!(
script(&steps),
"{++new++}{Ana (2026-01-02T03:04:00Z)} and {--old--}{Bo}."
);
}
#[test]
fn a_story_substitution_keeps_each_inline_date_when_written_back() {
let mut critic = Critic::default();
for (mark, tag, text) in [
(Ins, "header1#1@BO 2026-09-30T09:00:00Z", "new"),
(Del, "header1#2@AL 2026-09-29T14:05:00Z", "old"),
] {
critic.open(mark, Some(&format!("{TAG}{tag}")));
critic.raw(text);
critic.close(mark);
}
let story = critic.into_story();
let view = format!(
"---\nauthors:\n AL: Alice\n BO: Bob\nheaders:\n default: {{id: header1, text: \"{story}\"}}\n---\nBody.\n"
);
let written =
crate::markdown::markdown_to_docx(&view, &crate::markdown::DocxOptions::default())
.unwrap();
let package = crate::opc::PartFs::open(&written.docx).unwrap();
let xml = package.part_string("word/header1.xml").unwrap();
let header = super::super::ooxml::parse_xml(xml.as_bytes()).unwrap();
let paragraph = header
.elements()
.find(|element| element.local() == "p")
.unwrap();
let revisions: Vec<_> = paragraph
.elements()
.filter(|element| matches!(element.local(), "ins" | "del"))
.map(|element| {
(
element.local(),
element.attr("author"),
element.attr("date"),
)
})
.collect();
assert_eq!(
revisions,
[
("ins", Some("Bob"), Some("2026-09-30T09:00:00Z")),
("del", Some("Alice"), Some("2026-09-29T14:05:00Z")),
],
"{view}\n{xml}"
);
}
#[test]
fn adjacent_changes_keep_each_author_in_document_order() {
let same = [
("by+", "Ana"),
("t", "new"),
("close", "+"),
("by-", "Ana"),
("t", "old"),
("close", "-"),
];
assert_eq!(script(&same), "{++new++}{Ana}{--old--}{Ana}");
let different = [
("by+", "Bo"),
("t", "new"),
("close", "+"),
("by-", "Ana"),
("t", "old"),
("close", "-"),
];
assert_eq!(script(&different), "{++new++}{Bo}{--old--}{Ana}");
let one_side = [
("by+", "Bo"),
("t", "new"),
("close", "+"),
("open", "-"),
("t", "old"),
("close", "-"),
];
assert_eq!(script(&one_side), "{++new++}{Bo}{--old--}");
let other_side = [
("open", "+"),
("t", "new"),
("close", "+"),
("by-", "Ana"),
("t", "old"),
("close", "-"),
];
assert_eq!(script(&other_side), "{++new++}{--old--}{Ana}");
}
#[test]
fn neighbours_join_only_when_made_by_the_same_person_at_the_same_time() {
let same = [
("by+", "Ana"),
("t", "a"),
("close", "+"),
("by+", "Ana"),
("t", "b"),
("close", "+"),
];
assert_eq!(script(&same), "{++ab++}{Ana}");
let different = [
("by+", "Ana"),
("t", "a"),
("close", "+"),
("by+", "Bo"),
("t", "b"),
("close", "+"),
];
assert_eq!(script(&different), "{++a++}{Ana}{++b++}{Bo}");
}
#[test]
fn attributions_stay_with_their_change_inside_a_highlight() {
let steps = [
("open", "="),
("t", "a"),
("by+", "Bo"),
("t", "b"),
("close", "+"),
("note", "Ana: why?"),
("close", "="),
];
assert_eq!(script(&steps), "{==a{++b++}{Bo}==}{>>Ana: why?<<}");
}
#[test]
fn merged_nesting_keeps_the_outer_author_and_split_spans_keep_theirs() {
let nested = [
("by-", "Row"),
("t", "a"),
("by-", "Run"),
("t", "b"),
("close", "-"),
("close", "-"),
];
assert_eq!(script(&nested), "{--ab--}{Row}");
let crossing = [
("open", "="),
("t", "a"),
("by+", "Bo"),
("t", "b"),
("close", "="),
("t", "c"),
("close", "+"),
];
assert_eq!(script(&crossing), "{==a{++b++}{Bo}==}{++c++}{Bo}");
assert_eq!(script(&[("t", "x"), ("by+", "Bo"), ("close", "+")]), "x");
}
#[test]
fn a_tracked_break_extends_spans_only_by_the_same_person() {
let join = |out: &str, body: &str, change: Option<Change>| {
let mut out = out.to_string();
splice(&mut out, "\n\n", "", body, change.as_ref(), false);
out
};
let ana = || Some((Del, Some("Ana".to_string())));
assert_eq!(join("A", "B", ana()), "A{--\n\n--}{Ana}B");
assert_eq!(
join("{--A--}{Ana}", "{--B--}{Ana} rest", ana()),
"{--A\n\nB--}{Ana} rest"
);
assert_eq!(
join("{--A--}{Bo}", "{--B--}{Bo}", ana()),
"{--A--}{Bo}{--\n\n--}{Ana}{--B--}{Bo}"
);
assert_eq!(
join("A", "{--B--} rest", ana()),
"A{--\n\n--}{Ana}{--B--} rest"
);
assert_eq!(join("A", "{--B", ana()), "A{--\n\n--}{Ana}{--B");
}
#[test]
fn tree_ignores_a_close_with_nothing_open() {
assert_eq!(tree(vec![Token::Close(Ins)]), Vec::<Node>::new());
}
#[test]
fn review_5_literal_braces_are_not_whole_change_attributions() {
for literal in ["{X Y}", "{>>c0 @A: note<<}", "{r1 @A}{literal}"] {
assert_eq!(
whole_change(&format!("{{--a--}}{literal}")),
None,
"{literal}"
);
}
assert_eq!(
whole_change("{--a--}{r1 @A}"),
Some((Del, Some("r1 @A".into())))
);
}
#[test]
fn a_separator_next_to_a_wholly_changed_part_joins_its_change() {
let by = "{noid Alice}";
let joined = |parts: &[&str]| {
join_changed(parts.iter().map(|part| part.to_string()).collect(), "; ")
};
assert_eq!(
joined(&["in {++nested++}", &format!("{{--gone--}}{by}")]),
format!("in {{++nested++}}{{--; gone--}}{by}")
);
assert_eq!(
joined(&[&format!("{{--gone--}}{by}"), "kept", "{++new++}"]),
format!("{{--gone; --}}{by}kept{{++; new++}}")
);
assert_eq!(
joined(&["a {--b--}", "c {++d++} e"]),
"a {--b--}; c {++d++} e"
);
}
#[test]
fn a_change_inside_bold_text_keeps_one_bold_run() {
let mut critic = Critic::default();
critic.push("around ", true, false, None);
critic.open(Ins, Some("Ana"));
critic.push("an insertion", true, false, None);
critic.close(Ins);
critic.push(" inside", true, false, None);
critic.push(" end", false, false, None);
assert_eq!(md(critic), "**around {++an insertion++}{Ana} inside** end");
let mut critic = Critic::default();
critic.push("bold", true, false, None);
critic.open(Del, None);
critic.push(" plain", false, false, None);
critic.close(Del);
assert_eq!(md(critic), "**bold**{-- plain--}");
}
#[test]
fn markers_side_by_side_join_the_emphasis_together_or_not_at_all() {
let mut critic = Critic::default();
critic.open(Sc, None);
critic.push("varied ", false, false, None);
critic.push("Emphasis lives here. ", true, true, None);
critic.close(Sc);
critic.comment(&Note::same("c2 @AS: Testing."));
critic.push("See note.", true, true, None);
assert_eq!(
md(critic),
"{==varied **_Emphasis lives here._** ==}{>>c2 @AS: Testing.<<}**_See note._**"
);
let mut critic = Critic::default();
critic.push("bold ", true, false, None);
critic.comment(&Note::same("c0 @AS: Here."));
critic.push("text", true, false, None);
assert_eq!(md(critic), "**bold {>>c0 @AS: Here.<<}text**");
}
#[test]
fn a_change_inside_link_text_keeps_one_link() {
let mut critic = Critic::default();
let url = Some("https://example.com");
critic.push("the ", false, false, url);
critic.open(Ins, Some("Ana"));
critic.push("new ", false, false, url);
critic.close(Ins);
critic.push("page", false, false, url);
assert_eq!(md(critic), "[the {++new ++}{Ana}page](https://example.com)");
let mut critic = Critic::default();
critic.push("see ", false, false, None);
critic.open(Del, None);
critic.push("old", false, false, Some("https://a.example"));
critic.close(Del);
critic.push(" and ", false, false, Some("https://b.example"));
assert_eq!(
md(critic),
"see {--[old](https://a.example)--} [and](https://b.example)"
);
}
#[test]
fn a_delimiter_split_across_runs_is_escaped() {
assert_eq!(
script(&[("open", "-"), ("t", "a -"), ("t", "-} b"), ("close", "-")]),
"{--a --\\} b--}"
);
assert_eq!(
script(&[
("open", "-"),
("t", "x {"),
("open", "+"),
("close", "+"),
("t", "++ y"),
("close", "-")
]),
"{--x {\\++ y--}"
);
}
#[test]
fn a_note_prints_the_form_its_context_escapes() {
let note = Note {
prose: r"prose \ and \* form".to_string(),
code: r"code \ and * form".to_string(),
};
let mut prose = Critic::default();
prose.comment(¬e);
assert_eq!(md(prose), r"{>>prose \ and \* form<<}");
let mut code = Critic::default();
code.set_code_block();
code.comment(¬e);
assert_eq!(md(code), r"{>>code \ and * form<<}");
}
#[test]
fn a_code_block_breaks_only_the_delimiter_shapes_it_holds() {
let code = |t: &str| {
let mut critic = Critic::default();
critic.set_code_block();
text(&mut critic, t);
md(critic)
};
assert_eq!(code("fenced {++x++} code"), "fenced {\\++x++\\} code");
for (document, markdown) in [
(r"{\++x++}", r"{\\\++x++\}"),
(r"{\\++x++}", r"{\\\\\++x++\}"),
(r"\{++", r"\{\++"),
("a~>b", r"a~\>b"),
(r"a\~>b", r"a\~\>b"),
(r"back\slash", r"back\slash"),
(r"C:\path\x", r"C:\path\x"),
(r"\\d+", r"\\d+"),
(r"a\\b", r"a\\b"),
] {
assert_eq!(code(document), markdown, "{document}");
}
let mut critic = Critic::default();
critic.set_code_block();
critic.open(Ins, None);
text(&mut critic, "new {++x++}");
critic.close(Ins);
assert_eq!(md(critic), "{++new {\\++x++\\}++}");
let mut critic = Critic::default();
critic.set_code_block();
text(&mut critic, "old\\");
critic.open(Ins, None);
text(&mut critic, "new");
critic.close(Ins);
assert_eq!(md(critic), "old\\{++new++}");
let mut critic = Critic::default();
critic.set_code_block();
critic.open(Ins, None);
text(&mut critic, "new\\");
critic.close(Ins);
assert_eq!(md(critic), "{++new\\++}");
let mut critic = Critic::default();
critic.set_code_block();
critic.open(Ins, None);
text(&mut critic, "n");
critic.close(Ins);
critic.open(Del, None);
text(&mut critic, "old\\");
critic.close(Del);
assert_eq!(md(critic), "{++n++}{--old\\--}");
let mut critic = Critic::default();
critic.set_code_block();
critic.raw("$x_{--}$ and ");
assert_eq!(md(critic), "$x_{\\--}$ and ");
}
#[test]
fn the_writer_unwinds_the_code_escape_inside_a_fence() {
let fence = |code: &str| format!("```\n{code}\n```\n");
for document in [
"fenced {++x++} code",
"{\\++x++}",
"{\\\\++x++}",
"\\{++",
"a~>b",
"a\\~>b",
"back\\slash",
"C:\\path\\x",
"\\\\d+",
"a\\\\b",
] {
let source = fence(&escape_code(document));
assert_eq!(
crate::markdown::critic::encode(&source),
fence(document),
"{document}"
);
}
let mut critic = Critic::default();
critic.set_code_block();
critic.open(Ins, None);
text(&mut critic, "new");
critic.close(Ins);
assert_eq!(md(critic), "{++new++}");
}
#[test]
fn the_fence_escape_pair_is_exact() {
let fence = |code: &str| format!("```\n{code}\n```\n");
let unwind = |escaped: &str| {
let whole = crate::markdown::critic::encode(&fence(escaped));
whole["```\n".len()..whole.len() - "\n```\n".len()].to_string()
};
let shapes = [
("{", "++"),
("{", "--"),
("{", "~~"),
("{", ">>"),
("{", "=="),
("++", "}"),
("--", "}"),
("~~", "}"),
("<<", "}"),
("==", "}"),
("~", ">"),
];
let mut texts: Vec<String> = Vec::new();
for run in 0..5 {
let backslashes = "\\".repeat(run);
for (head, tail) in shapes {
texts.push(format!("a{head}{backslashes}{tail}b"));
texts.push(format!("{head}{backslashes}{tail}"));
texts.push(format!("x{backslashes} {head}{backslashes}{tail}"));
}
texts.push(format!("u{backslashes}v"));
}
texts.extend([
"{++x++}".to_string(),
"{\\\\}".to_string(),
"~~}".to_string(),
"{~~a~>b~~}".to_string(),
"C:\\path\\x".to_string(),
"\\\\d+".to_string(),
]);
for text in &texts {
let escaped = escape_code(text);
assert_eq!(unwind(&escaped), *text, "unwind(escape_code({text:?}))");
assert_eq!(
escape_code(&unwind(&escaped)),
escaped,
"escape_code(unwind({escaped:?}))"
);
}
}
}