use pulldown_cmark::{Event, Parser, Tag, TagEnd};
use std::ops::Range;
use super::write::parser_options;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[doc(hidden)]
pub enum Token {
InsertStart,
InsertEnd,
DeleteStart,
DeleteEnd,
SubstituteStart,
SubstituteSeparator,
SubstituteEnd,
HighlightStart,
HighlightEnd,
CommentStart,
CommentEnd,
AttributionStart,
ParagraphInsertion,
AttributionEnd,
CommentBreak,
MarkStart,
MarkEnd,
FieldStart,
FieldSeparator,
FieldEnd,
}
const STAND_INS: [(Token, char); 20] = [
(Token::InsertStart, '\u{2E0E}'),
(Token::InsertEnd, '\u{2E0F}'),
(Token::DeleteStart, '\u{2E10}'),
(Token::DeleteEnd, '\u{2E11}'),
(Token::SubstituteStart, '\u{2E12}'),
(Token::SubstituteSeparator, '\u{2E13}'),
(Token::SubstituteEnd, '\u{2E14}'),
(Token::HighlightStart, '\u{2E15}'),
(Token::HighlightEnd, '\u{2E16}'),
(Token::CommentStart, '\u{2E18}'),
(Token::CommentEnd, '\u{2E19}'),
(Token::AttributionStart, '\u{2E2F}'),
(Token::ParagraphInsertion, '\u{2E30}'),
(Token::AttributionEnd, '\u{2E31}'),
(Token::CommentBreak, '\u{2E2E}'),
(Token::MarkStart, '\u{2E1B}'),
(Token::MarkEnd, '\u{2E1E}'),
(Token::FieldStart, '\u{2E1F}'),
(Token::FieldSeparator, '\u{2E2A}'),
(Token::FieldEnd, '\u{2E2B}'),
];
pub(super) const ESCAPE: char = '\u{F0000}';
const SPANS: [(&str, &str, Option<&str>, Token, Token); 5] = [
("{++", "++}", None, Token::InsertStart, Token::InsertEnd),
("{--", "--}", None, Token::DeleteStart, Token::DeleteEnd),
(
"{~~",
"~~}",
Some("~>"),
Token::SubstituteStart,
Token::SubstituteEnd,
),
(
"{==",
"==}",
None,
Token::HighlightStart,
Token::HighlightEnd,
),
("{>>", "<<}", None, Token::CommentStart, Token::CommentEnd),
];
pub(super) fn stand_in(token: Token) -> char {
STAND_INS
.iter()
.find(|(t, _)| *t == token)
.map(|(_, c)| *c)
.unwrap_or(ESCAPE)
}
pub(super) fn token_of(c: char) -> Option<Token> {
STAND_INS.iter().find(|(_, s)| *s == c).map(|(t, _)| *t)
}
pub(super) fn push_escaped(out: &mut String, text: &str) {
for c in text.chars() {
if c == ESCAPE || token_of(c).is_some() {
out.push(ESCAPE);
}
out.push(c);
}
}
fn escaped(source: &str, at: usize) -> bool {
source[..at]
.bytes()
.rev()
.take_while(|b| *b == b'\\')
.count()
% 2
== 1
}
fn reference_stand_in(rest: &str) -> Option<usize> {
let semi = rest.as_bytes().iter().take(12).position(|&b| b == b';')?;
let number = rest.get(1..semi)?.strip_prefix('#')?;
let (digits, hex) = match number.strip_prefix(['x', 'X']) {
Some(hex) => (hex, true),
None => (number, false),
};
if digits.is_empty() || digits.len() > if hex { 6 } else { 7 } {
return None;
}
if !digits
.bytes()
.all(|b| b.is_ascii_digit() || hex && b.is_ascii_hexdigit())
{
return None;
}
let named = char::from_u32(u32::from_str_radix(digits, if hex { 16 } else { 10 }).ok()?)?;
(token_of(named).is_some() || named == ESCAPE).then_some(semi + 1)
}
#[cfg(test)]
pub(crate) fn encode(source: &str) -> String {
encode_spans(source, ALL, true)
}
pub(crate) struct ChangeRegion {
pub(crate) open: usize,
pub(crate) body: std::ops::Range<usize>,
pub(crate) split: Option<usize>,
pub(crate) close: usize,
pub(crate) inserted: bool,
}
pub(crate) fn change_regions(source: &str) -> Vec<ChangeRegion> {
let closers = Closers::new(source);
let mut regions = Vec::new();
let mut at = 0;
while at < source.len() {
if let Some(end) = closers.literal.verbatim_end(at) {
at = end;
continue;
}
let rest = &source[at..];
let here = if closers.literal.in_fence(at) {
ALL & !(MARK | FIELD)
} else {
ALL
};
let span = SPANS
.iter()
.find(|(open, ..)| rest.starts_with(*open))
.filter(|span| here & kind_of(span.3) != 0)
.filter(|_| !escaped(source, at))
.and_then(|&(open, close, separator, start, _)| {
let from = at + open.len();
let to = closers.find(close, from, source.len())?;
let split = match separator {
Some(separator) => Some((closers.find(separator, from, to)?, separator.len())),
None => None,
};
Some((from..to, to + close.len(), split, start))
});
match span {
Some((body, after, split, start)) => {
if kind_of(start) & CHANGES != 0 && !closers.literal.in_fence(at) {
regions.push(ChangeRegion {
open: at,
body,
split: split.map(|(mid, _)| mid),
close: after,
inserted: start == Token::InsertStart,
});
}
at = after;
}
None => {
let c = rest.chars().next().unwrap_or_default();
at += c.len_utf8();
}
}
}
regions
}
pub(super) fn legacy_attribution_error(source: &str) -> Option<String> {
let closers = Closers::new(source);
for (at, _) in source.match_indices("{>>") {
if escaped(source, at)
|| closers.literal.verbatim_end(at).is_some()
|| closers
.comments
.iter()
.any(|range| range.0 < at && at < range.1)
{
continue;
}
let encoded = encode_spans_kept(&source[..at]);
let before = encoded.trim_end_matches(['*', '_', '`']);
if ![Token::InsertEnd, Token::DeleteEnd, Token::SubstituteEnd]
.into_iter()
.any(|token| before.ends_with(stand_in(token)))
{
continue;
}
let Some((payload, _)) = source[at + 3..].split_once("<<}") else {
continue;
};
let tag_part = |part: &str| {
let id = part.split(' ').next().unwrap_or("");
let (story, id) = id
.rsplit_once('.')
.map_or((None, id), |(story, id)| (Some(story), id));
let numeric = id.strip_prefix('r').is_some_and(|ids| {
ids.split('+')
.all(|id| !id.is_empty() && id.bytes().all(|c| c.is_ascii_digit()))
});
numeric
&& story.is_none_or(|story| {
!story.is_empty()
&& story
.bytes()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-'))
})
&& super::view_notes::revision_tags(part).is_some_and(|tags| tags.len() == 1)
};
let plain_part = |part: &str| super::view_notes::plain_revision(part).is_some();
let chain = payload
.split(" on ")
.all(|part| tag_part(part) || plain_part(part));
let sides = !chain && payload.contains("; ") && payload.split("; ").all(plain_part);
if !chain && !sides {
continue;
}
let old = &source[at..at + 3 + payload.len() + 3];
let new = if chain {
let parts: Vec<&str> = payload.split(" on ").collect();
let nested = parts.len() > 1;
let spelled = parts
.iter()
.map(|&part| match () {
_ if tag_part(part) => part.to_string(),
_ if nested => super::from_docx::critic::spell_re_in_author(
&super::from_docx::critic::escaped_author(part),
),
_ => super::from_docx::critic::spell_re_in_author(part),
})
.collect::<Vec<_>>();
format!("{{{}}}", spelled.join(" re "))
} else {
let spelled = payload
.split("; ")
.map(super::from_docx::critic::spell_re_in_author)
.collect::<Vec<_>>();
format!("{{{}}}", spelled.join("; "))
};
let line = source[..at].bytes().filter(|&c| c == b'\n').count() + 1;
return Some(format!(
"line {line}: old attribution `{old}` is no longer supported; write `{new}`. A comment with that text is written `{{>>c1 @X: r1 @ASR<<}}`."
));
}
None
}
pub(crate) fn encode_checked(source: &str) -> (String, Vec<String>) {
let closers = Closers::new(source);
let mut check = Check::default();
let mut out = String::with_capacity(source.len());
encode_range(
source,
&closers,
0..source.len(),
ALL,
true,
&mut check,
&mut out,
);
check.consumed.sort_unstable();
check.consumed.dedup();
check.unclosed.sort_unstable();
check.unclosed.dedup();
let mut stray: Vec<(usize, &'static str)> = Vec::new();
for (slot, open, close) in SPANS
.iter()
.map(|&(open, close, ..)| (Closers::slot(close), open, close))
{
let escaped_openers: Vec<usize> = source
.match_indices(open)
.map(|(at, _)| at)
.filter(|&at| escaped(source, at) || closers.literal.verbatim_end(at).is_some())
.collect();
let mut used = 0;
for &at in &closers.positions[slot] {
if check.consumed.binary_search(&at).is_ok()
|| Closers::in_spans(&closers.comments, at)
|| Closers::in_spans(&closers.highlights, at)
{
continue;
}
if let Some(&opener) = escaped_openers.get(used)
&& opener < at
{
used += 1;
continue;
}
stray.push((at, close));
}
}
stray.sort_unstable();
stray.dedup();
let events: Vec<(usize, &'static str, &'static str, bool)> = check
.unclosed
.iter()
.map(|&(at, open, missing, separator)| (at, open, missing, separator))
.chain(stray.iter().map(|&(at, close)| (at, "", close, false)))
.collect();
let mut ordered = events;
ordered.sort_by_key(|&(at, ..)| at);
let mut warnings = Vec::with_capacity(ordered.len());
let mut line = 1;
let mut past = 0;
for (at, open, missing, separator) in ordered {
line += source[past..at].bytes().filter(|&b| b == b'\n').count();
past = at;
warnings.push(if open.is_empty() {
format!("'{missing}' with nothing open on line {line} is text")
} else if separator {
format!("'{open}' without its '{missing}' separator on line {line} is text")
} else {
format!("'{open}' without its '{missing}' on line {line} is text")
});
}
warnings.sort();
warnings.dedup();
(out, warnings)
}
type Allowed = u8;
const INSERT: Allowed = 1;
const DELETE: Allowed = 2;
const SUBSTITUTE: Allowed = 4;
const HIGHLIGHT: Allowed = 8;
const COMMENT: Allowed = 16;
const FIELD: Allowed = 32;
const MARK: Allowed = 64;
const CHANGES: Allowed = INSERT | DELETE | SUBSTITUTE;
const ALL: Allowed = CHANGES | HIGHLIGHT | COMMENT | FIELD | MARK;
fn kind_of(start: Token) -> Allowed {
match start {
Token::InsertStart => INSERT,
Token::DeleteStart => DELETE,
Token::SubstituteStart => SUBSTITUTE,
Token::HighlightStart => HIGHLIGHT,
_ => COMMENT,
}
}
fn inside(kind: Allowed, allowed: Allowed) -> Allowed {
match kind {
COMMENT => 0,
HIGHLIGHT => allowed & !HIGHLIGHT,
_ => allowed & !CHANGES,
}
}
type Cover = ((usize, usize), usize, usize);
type Run = (usize, usize, usize);
#[cfg(test)]
thread_local! {
static CLOSER_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
#[inline]
fn count_closer_steps(steps: usize) {
CLOSER_STEPS.with(|count| count.set(count.get() + steps));
}
#[cfg(not(test))]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
#[inline]
fn count_closer_steps(_steps: usize) {}
#[cfg(test)]
thread_local! {
static EDGE_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
#[inline]
fn count_edge_bytes(bytes: usize) {
EDGE_BYTES.with(|count| count.set(count.get() + bytes));
}
#[cfg(not(test))]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
#[inline]
fn count_edge_bytes(_bytes: usize) {}
struct Closers<'a> {
patterns: [&'a str; 6],
positions: [Vec<usize>; 6],
comments: Vec<(usize, usize)>,
highlights: Vec<(usize, usize)>,
cover: [Vec<Option<Cover>>; 6],
runs: [Vec<Option<Run>>; 6],
literal: Literal,
marks: Vec<usize>,
blanks: Vec<usize>,
fields: std::collections::HashMap<usize, usize>,
unwind: bool,
}
impl<'a> Closers<'a> {
fn new(source: &str) -> Self {
let literal = Literal::new(source);
let patterns = ["++}", "--}", "~~}", "==}", "<<}", "~>"];
let positions: [Vec<usize>; 6] = patterns.map(|pattern| {
source
.match_indices(pattern)
.map(|(at, _)| {
count_closer_steps(1);
at
})
.filter(|&at| {
(literal.in_code_fence(at) || !escaped(source, at))
&& literal.verbatim_end(at).is_none()
})
.collect()
});
let openers = |open: &str| -> Vec<usize> {
source
.match_indices(open)
.map(|(at, _)| {
count_closer_steps(1);
at
})
.filter(|&at| !escaped(source, at) && literal.verbatim_end(at).is_none())
.collect()
};
let comments = Self::paired(&openers("{>>"), "<<}", &[], &positions);
let highlights = Self::paired(&openers("{=="), "==}", &comments, &positions);
let mut nested = comments
.iter()
.chain(&highlights)
.copied()
.collect::<Vec<_>>();
nested.sort_unstable();
let mut cover: [Vec<Option<Cover>>; 6] = std::array::from_fn(|_| Vec::new());
let mut runs: [Vec<Option<Run>>; 6] = std::array::from_fn(|_| Vec::new());
for (slot, positions) in positions.iter().enumerate() {
let mut covered = Vec::with_capacity(positions.len());
let mut open: std::collections::VecDeque<(usize, usize)> =
std::collections::VecDeque::new();
let mut s = 0;
for &pos in positions {
count_closer_steps(1);
while s < nested.len() && nested[s].0 <= pos {
open.push_back(nested[s]);
s += 1;
}
while open.back().is_some_and(|&(_, end)| end <= pos) {
open.pop_back();
}
while open.front().is_some_and(|&(_, end)| end <= pos) {
open.pop_front();
}
covered.push(open.back().map(|&inner| {
(
inner,
open.front().copied().unwrap_or(inner).0,
open.iter().map(|&(_, end)| end).max().unwrap_or(0),
)
}));
}
let mut run = vec![None; positions.len()];
let mut i = 0;
while i < positions.len() {
count_closer_steps(1);
let Some((_, mut first, mut last)) = covered[i] else {
i += 1;
continue;
};
let mut j = i + 1;
while j < positions.len() {
count_closer_steps(1);
let Some((_, f, l)) = covered[j] else { break };
first = first.min(f);
last = last.max(l);
j += 1;
}
for item in run.iter_mut().take(j).skip(i) {
*item = Some((j, first, last));
}
i = j;
}
cover[slot] = covered;
runs[slot] = run;
}
let bytes = source.as_bytes();
let marks = (0..bytes.len())
.filter(|&at| {
count_closer_steps(1);
bytes[at..].starts_with(b"==") && mark_closes(source, &literal, at)
})
.collect();
let blanks = (0..bytes.len())
.filter(|&at| {
count_closer_steps(1);
bytes[at..].starts_with(b"\n\n")
})
.collect();
let fields = field_ends(source, &literal);
Self {
patterns,
positions,
comments,
highlights,
cover,
runs,
literal,
marks,
blanks,
fields,
unwind: true,
}
}
fn slot(pattern: &str) -> usize {
match pattern {
"++}" => 0,
"--}" => 1,
"~~}" => 2,
"==}" => 3,
"<<}" => 4,
"~>" => 5,
_ => unreachable!("unknown pattern {pattern}"),
}
}
fn in_spans(spans: &[(usize, usize)], at: usize) -> bool {
let i = spans.partition_point(|&(_, end)| end <= at);
spans.get(i).is_some_and(|&(start, _)| start <= at)
}
fn paired(
openers: &[usize],
close: &str,
inner: &[(usize, usize)],
positions: &[Vec<usize>; 6],
) -> Vec<(usize, usize)> {
let mut spans = Vec::new();
let closers = &positions[Self::slot(close)];
let mut at = 0;
for &opener in openers {
if Self::in_spans(&spans, opener) || Self::in_spans(inner, opener) {
continue;
}
at = at.max(closers.partition_point(|&c| c <= opener));
let close_at = loop {
count_closer_steps(1);
let Some(&c) = closers.get(at) else {
break None;
};
if Self::in_spans(inner, c) {
at += 1;
continue;
}
break Some(c);
};
if let Some(close_at) = close_at {
spans.push((opener, close_at + close.len()));
at += 1;
}
}
spans
}
fn keeping_fences(mut self) -> Self {
self.unwind = false;
self
}
fn find(&self, pattern: &str, from: usize, until: usize) -> Option<usize> {
count_closer_steps(1);
let slot = self.patterns.iter().position(|p| *p == pattern)?;
let positions = &self.positions[slot];
let at = *positions.get(positions.partition_point(|&at| at < from))?;
(at + pattern.len() <= until).then_some(at)
}
fn find_outside_nested(&self, pattern: &str, from: usize, until: usize) -> Option<usize> {
let slot = Self::slot(pattern);
let positions = &self.positions[slot];
let mut at = positions.partition_point(|&pos| pos < from);
loop {
count_closer_steps(1);
let pos = *positions.get(at)?;
if pos + pattern.len() > until {
return None;
}
let Some((inner, ..)) = self.cover[slot][at] else {
return Some(pos);
};
if inner.0 < from || inner.1 > until {
return Some(pos);
}
let (next, first, last) = self.runs[slot][at].expect("a covered position has a run");
at = if first >= from && last <= until {
next
} else {
positions.partition_point(|&p| p < inner.1)
};
}
}
fn paragraph_end(&self, from: usize, until: usize) -> usize {
count_closer_steps(1);
self.blanks
.get(self.blanks.partition_point(|&at| at < from))
.filter(|&&at| at + 2 <= until)
.map_or(until, |&at| at)
}
}
struct Literal {
verbatim: Vec<std::ops::Range<usize>>,
fences: Vec<std::ops::Range<usize>>,
front_matter: usize,
}
impl Literal {
fn new(source: &str) -> Self {
let mut literal = Self {
verbatim: Vec::new(),
fences: Vec::new(),
front_matter: 0,
};
let bytes = source.as_bytes();
let mut fence: Option<(u8, usize, usize)> = None;
let mut can_define = true;
let destinations = destination_ends(source);
let mut line_start = 0;
if source.starts_with("---\n") || source.starts_with("---\r\n") {
let mut end = source.find('\n').map_or(source.len(), |n| n + 1);
while end < source.len() {
let line_end = source[end..].find('\n').map_or(source.len(), |n| end + n);
let closes = matches!(source[end..line_end].trim_end(), "---" | "...");
end = (line_end + 1).min(source.len());
if closes {
literal.fences.push(0..line_end);
literal.front_matter = line_end;
line_start = end;
break;
}
}
}
let mut at = line_start;
while at < bytes.len() {
if at == line_start {
let line_end = source[at..].find('\n').map_or(bytes.len(), |n| at + n);
let line = &source[at..line_end];
let indent = line.len() - line.trim_start().len();
let run = |b: u8| line.bytes().skip(indent).take_while(|&c| c == b).count();
match fence {
Some((b, width, start)) => {
if indent < 4
&& run(b) >= width
&& line[indent + run(b)..].trim().is_empty()
{
literal.fences.push(start..line_end);
fence = None;
}
can_define = true;
at = line_end + 1;
line_start = at;
continue;
}
None => {
for b in *b"`~" {
let width = run(b);
let info = &line[indent + width..];
if indent < 4 && width >= 3 && !(b == b'`' && info.contains('`')) {
fence = Some((b, width, at));
}
}
let destination =
can_define.then(|| definition_destination(line)).flatten();
can_define = fence.is_some()
|| destination.is_some()
|| line.trim().is_empty()
|| line.trim_start().starts_with('#');
if let Some(from) = destination {
literal.verbatim.push(at + from..line_end);
}
if fence.is_some() || destination.is_some() {
at = line_end + 1;
line_start = at;
continue;
}
}
}
}
let from = at;
let end = match bytes[at] {
b'`' if !escaped(source, at) => code_span_end(source, at),
b'(' if at > 0 && bytes[at - 1] == b']' && !escaped(source, at - 1) => {
destinations.get(&(at + 1)).copied()
}
b'<' if !escaped(source, at) => autolink_end(source, at),
_ => None,
};
match end {
Some(end) => {
literal.verbatim.push(at..end);
at = end;
}
None if bytes[at] == b'`' => {
at += bytes[at..].iter().take_while(|&&b| b == b'`').count();
}
None => at += source[at..].chars().next().map_or(1, char::len_utf8),
}
if let Some(n) = source[from..at].rfind('\n') {
line_start = from + n + 1;
}
}
if let Some((.., start)) = fence {
literal.fences.push(start..bytes.len());
}
literal.verbatim.extend(indented_code(source));
literal.verbatim.sort_by_key(|range| range.start);
literal
}
fn verbatim_end(&self, at: usize) -> Option<usize> {
let i = self.verbatim.partition_point(|r| r.end <= at);
self.verbatim
.get(i)
.filter(|r| r.start <= at)
.map(|r| r.end)
}
fn in_fence(&self, at: usize) -> bool {
let i = self.fences.partition_point(|r| r.end <= at);
self.fences.get(i).is_some_and(|r| r.start <= at)
}
fn in_code_fence(&self, at: usize) -> bool {
self.in_fence(at) && at >= self.front_matter
}
}
fn indented_code(source: &str) -> Vec<std::ops::Range<usize>> {
use pulldown_cmark::{CodeBlockKind, Event, Parser, Tag};
if !source
.lines()
.any(|line| line.starts_with(" ") || line.starts_with('\t'))
{
return Vec::new();
}
Parser::new_ext(source, super::write::parser_options())
.into_offset_iter()
.filter_map(|(event, range)| {
matches!(event, Event::Start(Tag::CodeBlock(CodeBlockKind::Indented))).then_some(range)
})
.collect()
}
fn code_span_end(source: &str, at: usize) -> Option<usize> {
let bytes = source.as_bytes();
let width = bytes[at..].iter().take_while(|&&b| b == b'`').count();
let mut i = at + width;
while i < bytes.len() {
if bytes[i] == b'`' {
let run = bytes[i..].iter().take_while(|&&b| b == b'`').count();
if run == width {
return Some(i + run);
}
i += run;
} else if bytes[i..].starts_with(b"\n\n") {
return None;
} else {
i += 1;
}
}
None
}
fn definition_destination(line: &str) -> Option<usize> {
let indent = line.len() - line.trim_start_matches(' ').len();
let label = line.get(indent..)?.strip_prefix('[')?;
if indent > 3 || label.starts_with('^') {
return None;
}
let mut chars = label.char_indices();
while let Some((i, c)) = chars.next() {
match c {
'\\' => {
chars.next();
}
'[' => return None,
']' => {
return (i > 0 && label[i + 1..].starts_with(':')).then_some(indent + 1 + i + 2);
}
_ => {}
}
}
None
}
fn destination_ends(source: &str) -> std::collections::HashMap<usize, usize> {
let mut ends = std::collections::HashMap::new();
let mut line_start = 0;
for line in source.split('\n') {
let mut levels = Vec::new();
let mut starts = Vec::new();
let (mut level, mut backslashes) = (0i64, 0usize);
let (mut bracket, mut opened) = (false, false);
for (i, c) in line.char_indices() {
count_closer_steps(1);
let at = line_start + i;
if opened {
starts.push(at);
}
let free = backslashes % 2 == 0;
let before = level;
if free {
match c {
'(' => level += 1,
')' => level -= 1,
_ => {}
}
}
opened = bracket && c == '(';
bracket = free && c == ']';
backslashes = if c == '\\' { backslashes + 1 } else { 0 };
levels.push((at, before, level));
}
let mut nearest = std::collections::HashMap::new();
let mut starts = starts.iter().rev().peekable();
for &(at, before, after) in levels.iter().rev() {
count_closer_steps(1);
nearest.insert(after, at);
if starts.next_if(|&&s| s == at).is_some()
&& let Some(&end) = nearest.get(&(before - 1))
{
ends.insert(at, end);
}
}
line_start += line.len() + 1;
}
ends
}
fn comment_end(source: &str, at: usize) -> Option<usize> {
if !source[at..].starts_with("<!--") {
return None;
}
source[at + 4..].find("-->").map(|close| at + 4 + close + 3)
}
fn autolink_end(source: &str, at: usize) -> Option<usize> {
let rest = &source[at + 1..];
let scheme = rest
.bytes()
.take_while(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'.' | b'-'))
.count();
if !(2..=32).contains(&scheme) || rest.as_bytes().get(scheme) != Some(&b':') {
return None;
}
let close = rest.find(|c: char| c == '>' || c == '<' || c.is_whitespace())?;
(rest.as_bytes()[close] == b'>').then_some(at + 1 + close + 1)
}
#[derive(Default)]
struct Check {
unclosed: Vec<(usize, &'static str, &'static str, bool)>,
consumed: Vec<usize>,
}
fn encode_spans_checked(source: &str, allowed: Allowed, labels: bool, check: &mut Check) -> String {
let mut out = String::with_capacity(source.len());
encode_range(
source,
&Closers::new(source),
0..source.len(),
allowed,
labels,
check,
&mut out,
);
out
}
fn encode_spans(source: &str, allowed: Allowed, labels: bool) -> String {
encode_spans_checked(source, allowed, labels, &mut Check::default())
}
fn encode_spans_kept(source: &str) -> String {
let mut out = String::with_capacity(source.len());
encode_range(
source,
&Closers::new(source).keeping_fences(),
0..source.len(),
ALL,
false,
&mut Check::default(),
&mut out,
);
out
}
fn encode_range(
source: &str,
closers: &Closers<'_>,
range: std::ops::Range<usize>,
allowed: Allowed,
labels: bool,
check: &mut Check,
out: &mut String,
) {
let mut at = range.start;
while at < range.end {
if let Some(end) = closers
.literal
.verbatim_end(at)
.filter(|&end| end <= range.end)
{
push_escaped(out, &source[at..end]);
at = end;
continue;
}
let rest = &source[at..range.end];
let here = if closers.literal.in_fence(at) {
allowed & !(MARK | FIELD)
} else {
allowed
};
if closers.unwind
&& closers.literal.in_code_fence(at)
&& let Some((text, len)) = fence_escape_at(source, at)
{
push_escaped(out, &text);
at += len;
continue;
}
let paragraph = rest.starts_with("¶{") && !escaped(source, at);
let tag_at = at + if paragraph { "¶".len() } else { 0 };
let before = out.trim_end_matches(['*', '_', '`']);
let follows = [
Token::AttributionEnd,
Token::InsertEnd,
Token::DeleteEnd,
Token::SubstituteEnd,
]
.into_iter()
.any(|token| before.ends_with(stand_in(token)));
if (paragraph || follows)
&& !escaped(source, tag_at)
&& let Some((note, width)) = attribution_tag(&source[tag_at..range.end])
{
out.push(stand_in(if paragraph {
Token::ParagraphInsertion
} else {
Token::AttributionStart
}));
encode_comment(source, closers, tag_at + 1..tag_at + 1 + note.len(), out);
out.push(stand_in(Token::AttributionEnd));
at = tag_at + width;
continue;
}
let span = SPANS
.iter()
.find(|(open, ..)| rest.starts_with(open))
.filter(|span| allowed & kind_of(span.3) != 0)
.filter(|_| closers.literal.in_code_fence(at) || !escaped(source, at))
.and_then(|&(open, close, separator, start, end)| {
let from = at + open.len();
let skip_nested = start != Token::CommentStart;
let to = if skip_nested {
closers.find_outside_nested(close, from, range.end)
} else {
closers.find(close, from, range.end)
};
let Some(to) = to else {
check.unclosed.push((at, open, close, false));
return None;
};
check.consumed.push(to);
let split = match separator {
Some(separator) => {
let mid = if skip_nested {
closers.find_outside_nested(separator, from, to)
} else {
closers.find(separator, from, to)
};
match mid {
Some(mid) => {
check.consumed.push(mid);
Some((mid, separator.len()))
}
None => {
check.unclosed.push((at, open, separator, true));
return None;
}
}
}
None => None,
};
Some((from..to, to + close.len(), split, start, end))
});
match span {
Some((mut body, after, split, start, end)) => {
let nested = inside(kind_of(start), allowed);
if labels
&& start != Token::CommentStart
&& (at == 0 || source[..at].ends_with('\n'))
&& let Some(label) = footnote_label(&source[body.clone()])
&& split.is_none_or(|(mid, _)| mid >= body.start + label.len())
{
push_escaped(out, label);
body.start += label.len();
}
out.push(stand_in(start));
match split {
Some((mid, width)) => {
encode_range(source, closers, body.start..mid, nested, false, check, out);
out.push(stand_in(Token::SubstituteSeparator));
encode_range(
source,
closers,
mid + width..body.end,
nested,
false,
check,
out,
);
}
None if start == Token::CommentStart => {
encode_comment(source, closers, body, out);
}
None => encode_range(source, closers, body, nested, false, check, out),
}
out.push(stand_in(end));
at = after;
}
None => {
if here & FIELD != 0
&& let Some((code, end)) = field_at(source, closers, at, range.end)
{
out.push(stand_in(Token::FieldStart));
for c in source[code.clone()].trim().chars() {
if c.is_ascii_punctuation() {
out.push('\\');
}
push_escaped(out, c.encode_utf8(&mut [0; 4]));
}
out.push(stand_in(Token::FieldSeparator));
encode_range(
source,
closers,
code.end + 1..end,
allowed,
labels,
check,
out,
);
out.push(stand_in(Token::FieldEnd));
at = end + FIELD_END.len();
continue;
}
if here & MARK != 0
&& let Some(close) = mark_close(source, closers, at, range.end)
{
out.push(stand_in(Token::MarkStart));
encode_range(source, closers, at + 2..close, allowed, false, check, out);
out.push(stand_in(Token::MarkEnd));
at = close + 2;
continue;
}
let c = rest.chars().next().unwrap_or_default();
if c == '&'
&& !escaped(source, at)
&& !closers.literal.in_fence(at)
&& let Some(len) = reference_stand_in(rest)
{
out.push(ESCAPE);
push_escaped(out, &rest[..len]);
at += len;
continue;
}
push_escaped(out, &rest[..c.len_utf8()]);
at += c.len_utf8();
}
}
}
}
fn recognized_note(note: &str) -> bool {
fn parses(text: &str) -> bool {
super::view_notes::revision_tags(text).is_some()
|| super::view_notes::nested_revision_tags(text).is_some()
|| super::view_notes::plain_revisions(text).is_some()
|| super::view_notes::nested_plain_revisions(text).is_some()
}
if parses(note) {
return true;
}
note.contains(" move") && parses(¬e_without_move(note))
}
fn note_without_move(note: &str) -> String {
note.split(" re ")
.map(|segment| {
segment
.split("; ")
.map(part_without_move)
.collect::<Vec<_>>()
.join("; ")
})
.collect::<Vec<_>>()
.join(" re ")
}
fn part_without_move(part: &str) -> String {
let part = part.trim();
if let Some((body, name)) = part.rsplit_once(" move ") {
let name = name.trim();
if !name.is_empty() && !name.contains(char::is_whitespace) {
return body.trim_end().to_string();
}
}
part.strip_suffix(" move").unwrap_or(part).to_string()
}
pub(crate) fn attribution_tag(text: &str) -> Option<(&str, usize)> {
let after = text.strip_prefix('{')?;
let end = after.char_indices().find_map(|(at, c)| {
(matches!(c, '}' | '{' | '\n') && !escaped(text, at + 1)).then_some((at, c))
})?;
if end.1 != '}' {
return None;
}
let end = end.0;
let note = &after[..end];
recognized_note(note).then_some((note, end + 2))
}
pub(crate) fn attributed_notes(source: &str) -> Vec<(Token, String)> {
touching_notes(source)
.into_iter()
.map(|(token, note, _)| (token, note))
.collect()
}
pub(crate) fn touching_notes(source: &str) -> Vec<(Token, String, bool)> {
let mut notes = Vec::new();
let mut closer = Token::InsertEnd;
let mut note = None;
let mut gap = true;
let mut open = false;
let mut touches = false;
Pieces::default().feed(&encode_spans_kept(source), |piece| match piece {
Piece::Token(Token::InsertStart | Token::DeleteStart | Token::SubstituteStart) => {
if !open {
touches = !gap;
open = true;
}
}
Piece::Token(token @ (Token::InsertEnd | Token::DeleteEnd | Token::SubstituteEnd)) => {
closer = token;
open = false;
}
Piece::Token(Token::AttributionStart) => note = Some((closer, String::new(), touches)),
Piece::Token(Token::ParagraphInsertion) => {
note = Some((Token::ParagraphInsertion, String::new(), !gap));
}
Piece::Token(Token::AttributionEnd) => {
if let Some(note) = note.take() {
notes.push(note);
}
gap = false;
}
Piece::Text(text) => match &mut note {
Some((_, note, _)) => note.push_str(text),
None if !open && !text.is_empty() => gap = true,
None => {}
},
Piece::Token(_) if !open => gap = true,
_ => {}
});
notes
}
pub(crate) fn without_attributions(source: &str) -> String {
let mut out = String::new();
let mut inside = false;
Pieces::default().feed(&encode_spans_kept(source), |piece| match piece {
Piece::Token(Token::AttributionStart | Token::ParagraphInsertion) => inside = true,
Piece::Token(Token::AttributionEnd) => inside = false,
Piece::Text(text) if !inside => out.push_str(text),
Piece::Token(token) if !inside => out.push_str(delimiter(token)),
_ => {}
});
out
}
struct CommentMark {
start: Token,
end: Token,
inner: std::ops::Range<usize>,
split: Option<(usize, usize)>,
after: usize,
}
fn comment_change(source: &str, at: usize, until: usize) -> Option<CommentMark> {
if escaped(source, at) {
return None;
}
let rest = source.get(at..until)?;
let (open, close, separator, start, end) = if rest.starts_with("{++") {
("{++", "++}", None, Token::InsertStart, Token::InsertEnd)
} else if rest.starts_with("{--") {
("{--", "--}", None, Token::DeleteStart, Token::DeleteEnd)
} else if rest.starts_with("{~~") {
(
"{~~",
"~~}",
Some("~>"),
Token::SubstituteStart,
Token::SubstituteEnd,
)
} else {
return None;
};
let body = at + open.len();
let close_at = comment_closer(source, open, close, body, until)?;
let split = match separator {
Some(separator) => {
let mid = comment_separator(source, open, close, separator, body, close_at)?;
Some((mid, separator.len()))
}
None => None,
};
Some(CommentMark {
start,
end,
inner: body..close_at,
split,
after: close_at + close.len(),
})
}
fn comment_closer(
source: &str,
open: &str,
close: &str,
from: usize,
until: usize,
) -> Option<usize> {
let mut depth = 1usize;
let mut at = from;
while at < until {
if !escaped(source, at) && source[at..].starts_with(open) {
depth += 1;
at += open.len();
continue;
}
if !escaped(source, at) && source[at..].starts_with(close) {
depth -= 1;
if depth == 0 {
return Some(at);
}
at += close.len();
continue;
}
at += source[at..].chars().next()?.len_utf8();
}
None
}
fn comment_separator(
source: &str,
open: &str,
close: &str,
separator: &str,
from: usize,
until: usize,
) -> Option<usize> {
let mut depth = 1usize;
let mut at = from;
while at < until {
if !escaped(source, at) && source[at..].starts_with(open) {
depth += 1;
at += open.len();
continue;
}
if !escaped(source, at) && source[at..].starts_with(close) {
depth -= 1;
if depth == 0 {
return None;
}
at += close.len();
continue;
}
if depth == 1 && !escaped(source, at) && source[at..].starts_with(separator) {
return Some(at);
}
at += source[at..].chars().next()?.len_utf8();
}
None
}
fn encode_comment(
source: &str,
closers: &Closers<'_>,
body: std::ops::Range<usize>,
out: &mut String,
) {
let mut at = body.start;
while at < body.end {
if closers.unwind
&& closers.literal.in_code_fence(at)
&& let Some((text, len)) = fence_escape_at(&source[..body.end], at)
{
push_escaped(out, &text);
at += len;
continue;
}
if source.as_bytes()[at] == b'&'
&& let Some(len) = reference_stand_in(&source[at..body.end])
{
out.push(ESCAPE);
push_escaped(out, &source[at..at + len]);
at += len;
continue;
}
if source.as_bytes()[at] == b'\n' {
let rest = &source[at + 1..body.end];
let white = rest.len() - rest.trim_start_matches([' ', '\t', '\r', '\n']).len();
if rest[..white].contains('\n') {
out.push(stand_in(Token::CommentBreak));
at += 1 + white;
continue;
}
}
if let Some(CommentMark {
start,
end,
inner,
split,
after,
}) = comment_change(source, at, body.end)
{
out.push(stand_in(start));
if let Some((mid, width)) = split {
encode_comment(source, closers, inner.start..mid, out);
out.push(stand_in(Token::SubstituteSeparator));
encode_comment(source, closers, mid + width..inner.end, out);
} else {
encode_comment(source, closers, inner, out);
}
out.push(stand_in(end));
at = after;
continue;
}
let c = source[at..body.end].chars().next().unwrap_or_default();
push_escaped(out, &source[at..at + c.len_utf8()]);
at += c.len_utf8();
}
}
fn fence_escape_at(source: &str, at: usize) -> Option<(String, usize)> {
const OPENER: [&str; 5] = ["++", "--", "~~", ">>", "=="];
const CLOSER: [&str; 5] = ["++", "--", "~~", "<<", "=="];
let bytes = source.as_bytes();
if bytes.get(at) == Some(&b'\\') {
let run = bytes[at..].iter().take_while(|&&b| b == b'\\').count();
if let Some((_, width)) = attribution_tag(&source[at + run..]) {
let kept = if run % 2 == 1 { (run - 1) / 2 } else { run };
return Some((
format!(
"{}{}",
"\\".repeat(kept),
&source[at + run..at + run + width]
),
run + width,
));
}
}
let (head, run, tail) = {
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| source[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| source[at..].starts_with(head)) {
shape(2, &["}"])
} else if bytes.get(at) == Some(&b'~') {
shape(1, &[">"])
} else {
None
}
}?;
if run == 0 {
return None;
}
let whole = head + run + tail;
let mut text = String::with_capacity(whole);
if run % 2 == 0 {
text.push_str(&source[at..at + whole]);
} else {
text.push_str(&source[at..at + head]);
for _ in 0..(run - 1) / 2 {
text.push('\\');
}
text.push_str(&source[at + head + run..at + whole]);
}
Some((text, whole))
}
const FIELD_END: &str = "{/}";
const FIELD_NAMES: [&str; 76] = [
"ADDRESSBLOCK",
"ADVANCE",
"ASK",
"AUTHOR",
"AUTONUM",
"AUTONUMLGL",
"AUTONUMOUT",
"AUTOTEXT",
"AUTOTEXTLIST",
"BARCODE",
"BIBLIOGRAPHY",
"BIDIOUTLINE",
"CITATION",
"COMMENTS",
"COMPARE",
"CREATEDATE",
"DATABASE",
"DATE",
"DISPLAYBARCODE",
"DOCPROPERTY",
"DOCVARIABLE",
"EDITTIME",
"EQ",
"FILENAME",
"FILESIZE",
"FILLIN",
"FORMCHECKBOX",
"FORMDROPDOWN",
"FORMTEXT",
"GOTOBUTTON",
"GREETINGLINE",
"HYPERLINK",
"IF",
"INCLUDEPICTURE",
"INCLUDETEXT",
"INDEX",
"INFO",
"KEYWORDS",
"LASTSAVEDBY",
"LINK",
"LISTNUM",
"MACROBUTTON",
"MERGEBARCODE",
"MERGEFIELD",
"MERGEREC",
"MERGESEQ",
"NEXT",
"NEXTIF",
"NOTEREF",
"NUMCHARS",
"NUMPAGES",
"NUMWORDS",
"PAGE",
"PAGEREF",
"PRINT",
"PRINTDATE",
"QUOTE",
"RD",
"REF",
"REVNUM",
"SAVEDATE",
"SECTION",
"SECTIONPAGES",
"SEQ",
"SET",
"SKIPIF",
"STYLEREF",
"SUBJECT",
"SYMBOL",
"TA",
"TC",
"TEMPLATE",
"TIME",
"TITLE",
"TOA",
"TOC",
];
pub(crate) fn is_field_code(code: &str) -> bool {
let code = code.trim();
let name = code.split([' ', '\\']).next().unwrap_or_default();
let closed = format!("{code}}}");
field_code_close(closed.char_indices()) == Some(code.len())
&& FIELD_NAMES.iter().any(|f| f.eq_ignore_ascii_case(name))
}
const LONGEST_FIELD_CODE: usize = 1024;
pub(crate) fn field_code_close(chars: impl Iterator<Item = (usize, char)>) -> Option<usize> {
let mut quoted = false;
let mut backslash = false;
for (at, c) in chars.take(LONGEST_FIELD_CODE) {
match c {
'\n' | '\r' => return None,
'"' if !backslash => quoted = !quoted,
'{' if !quoted => return None,
'}' if !quoted => return Some(at),
_ => {}
}
backslash = c == '\\' && !backslash;
}
None
}
fn field_code(source: &str, at: usize, until: usize) -> Option<std::ops::Range<usize>> {
let rest = source.get(at..until)?;
if !rest.starts_with('{') || escaped(source, at) {
return None;
}
let close = 1 + field_code_close(rest[1..].char_indices())?;
is_field_code(&rest[1..close]).then_some(at + 1..at + close)
}
fn field_at(
source: &str,
closers: &Closers<'_>,
at: usize,
until: usize,
) -> Option<(std::ops::Range<usize>, usize)> {
let code = field_code(source, at, until)?;
count_closer_steps(1);
let end = *closers.fields.get(&at)?;
(end + FIELD_END.len() <= until).then_some((code, end))
}
fn field_ends(source: &str, literal: &Literal) -> std::collections::HashMap<usize, usize> {
let mut ends = std::collections::HashMap::new();
let mut open: Vec<usize> = Vec::new();
let mut i = 0;
while i < source.len() {
count_closer_steps(1);
if let Some(skip) = literal.verbatim_end(i) {
i = skip;
} else if literal.in_fence(i) {
open.clear();
i += source[i..].chars().next().map_or(1, char::len_utf8);
} else if source[i..].starts_with("\n\n") {
open.retain(|&start| opens_paragraph(source, start));
i += 1;
} else if source[i..].starts_with(FIELD_END) && !escaped(source, i) {
if let Some(start) = open.pop() {
ends.insert(start, i);
}
i += FIELD_END.len();
} else if let Some(code) = field_code(source, i, source.len()) {
open.push(i);
i = code.end + 1;
} else {
i += source[i..].chars().next().map_or(1, char::len_utf8);
}
}
ends
}
fn opens_paragraph(source: &str, at: usize) -> bool {
let line = &source[source[..at].rfind('\n').map_or(0, |n| n + 1)..at];
let mut rest = line.trim_start();
loop {
let marker = if let Some(after) = rest.strip_prefix('>') {
after
} else if rest.starts_with('#') {
rest.trim_start_matches('#')
.strip_prefix(' ')
.unwrap_or(rest)
} else if let Some(after) = rest.strip_prefix(['-', '*', '+']) {
after.strip_prefix(' ').unwrap_or(rest)
} else {
let digits = rest.len() - rest.trim_start_matches(|c: char| c.is_ascii_digit()).len();
rest[digits..]
.strip_prefix(['.', ')'])
.filter(|_| digits > 0)
.and_then(|after| after.strip_prefix(' '))
.unwrap_or(rest)
};
if marker.len() == rest.len() {
return rest.is_empty();
}
rest = marker.trim_start();
}
}
fn mark_close(source: &str, closers: &Closers<'_>, at: usize, until: usize) -> Option<usize> {
let bytes = source.as_bytes();
let is = |i: usize, b: u8| i < bytes.len() && bytes[i] == b;
let blank = |i: usize| i >= bytes.len() || bytes[i].is_ascii_whitespace();
let opens = source[at..until].starts_with("==")
&& !escaped(source, at)
&& !(at > 0 && (is(at - 1, b'=') || is(at - 1, b'{')))
&& !is(at + 2, b'=')
&& !is(at + 2, b'}')
&& !blank(at + 2);
if !opens {
return None;
}
let end = closers.paragraph_end(at + 2, until);
let from = at + 2 + source[at + 2..].chars().next().map_or(1, char::len_utf8);
let marks = &closers.marks;
count_closer_steps(1);
let close = *marks.get(marks.partition_point(|&close| close < from))?;
(close + 2 <= end).then_some(close)
}
fn mark_closes(source: &str, literal: &Literal, close: usize) -> bool {
let bytes = source.as_bytes();
let is = |i: usize, b: u8| i < bytes.len() && bytes[i] == b;
let blank = |i: usize| i >= bytes.len() || bytes[i].is_ascii_whitespace();
close > 0
&& !blank(close - 1)
&& !is(close - 1, b'=')
&& !is(close + 2, b'=')
&& !is(close + 2, b'}')
&& !escaped(source, close)
&& literal.verbatim_end(close).is_none()
&& !literal.in_fence(close)
}
fn footnote_label(text: &str) -> Option<&str> {
let name = text.strip_prefix("[^")?;
let close = name.find(']')?;
if close == 0 || name[..close].contains(char::is_whitespace) {
return None;
}
let after = name[close..].strip_prefix("]:")?;
let spaces = after.len() - after.trim_start_matches([' ', '\t']).len();
Some(&text[..2 + close + 2 + spaces])
}
#[doc(hidden)]
pub fn encode_spans_only(source: &str) -> String {
encode_spans(source, ALL, false)
}
pub(super) fn verbatim_ranges(source: &str) -> Vec<std::ops::Range<usize>> {
let mut ranges = Literal::new(source).verbatim;
let mut at = 0;
while let Some(open) = source[at..].find("<!--") {
let open = at + open;
match comment_end(source, open) {
Some(end) => {
ranges.push(open..end);
at = end;
}
None => at = open + "<!--".len(),
}
}
ranges.sort_by_key(|range| range.start);
let mut disjoint: Vec<std::ops::Range<usize>> = Vec::with_capacity(ranges.len());
for range in ranges {
match disjoint.last_mut() {
Some(last) if last.end >= range.start => last.end = last.end.max(range.end),
_ => disjoint.push(range),
}
}
disjoint
}
pub(crate) fn decode(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut pieces = Pieces::default();
pieces.feed(text, |piece| match piece {
Piece::Text(text) => out.push_str(text),
Piece::Token(Token::CommentBreak) => out.push(' '),
Piece::Token(_) => {}
});
out
}
pub(crate) fn restore(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut pieces = Pieces::default();
pieces.feed(text, |piece| match piece {
Piece::Text(text) => out.push_str(text),
Piece::Token(token) => out.push_str(delimiter(token)),
});
out
}
#[doc(hidden)]
pub fn delimiter(token: Token) -> &'static str {
match token {
Token::InsertStart => "{++",
Token::InsertEnd => "++}",
Token::DeleteStart => "{--",
Token::DeleteEnd => "--}",
Token::SubstituteStart => "{~~",
Token::SubstituteSeparator => "~>",
Token::SubstituteEnd => "~~}",
Token::HighlightStart => "{==",
Token::HighlightEnd => "==}",
Token::AttributionStart => "{",
Token::ParagraphInsertion => "¶{",
Token::AttributionEnd => "}",
Token::CommentStart => "{>>",
Token::CommentEnd => "<<}",
Token::CommentBreak => "\n\n",
Token::FieldStart => "{",
Token::FieldSeparator => "}",
Token::FieldEnd => FIELD_END,
Token::MarkStart | Token::MarkEnd => "==",
}
}
#[derive(Debug, PartialEq, Eq)]
#[doc(hidden)]
pub enum Piece<'a> {
Text(&'a str),
Token(Token),
}
#[derive(Default)]
#[doc(hidden)]
pub struct Pieces {
escape_pending: bool,
}
impl Pieces {
#[doc(hidden)]
pub fn feed(&mut self, text: &str, mut emit: impl FnMut(Piece<'_>)) {
let mut start = 0;
for (at, c) in text.char_indices() {
if self.escape_pending {
self.escape_pending = false;
start = at;
continue;
}
if c == ESCAPE {
if start < at {
emit(Piece::Text(&text[start..at]));
}
self.escape_pending = true;
start = at + c.len_utf8();
continue;
}
if let Some(token) = token_of(c) {
if start < at {
emit(Piece::Text(&text[start..at]));
}
emit(Piece::Token(token));
start = at + c.len_utf8();
}
}
if start < text.len() {
emit(Piece::Text(&text[start..]));
}
}
}
pub(super) fn math_crosses_boundary(latex: &str) -> bool {
let mut open = Vec::new();
let mut crosses = false;
Pieces::default().feed(latex, |piece| {
if let Piece::Token(token) = piece {
match token {
Token::InsertStart => open.push(Token::InsertEnd),
Token::DeleteStart => open.push(Token::DeleteEnd),
Token::InsertEnd | Token::DeleteEnd => {
crosses |= open.pop() != Some(token);
}
_ => crosses = true,
}
}
});
crosses || !open.is_empty()
}
pub(crate) fn resolve(markdown: &str, accept: bool) -> String {
let candidate = resolved_slice(markdown, accept);
super::repair::repair(markdown, &candidate, accept)
}
pub(super) fn resolved_slice(markdown: &str, accept: bool) -> String {
let merged = merge_seam_levels(markdown, accept);
resolve_with_policy(&merged, accept, false)
}
pub(super) fn member_span_ranges(source: &str) -> Vec<Range<usize>> {
member_spans(source)
.iter()
.map(|span| span.range.clone())
.collect()
}
pub(super) fn resolved_regions(source: &str) -> Vec<Range<usize>> {
let mut ranges: Vec<Range<usize>> = change_regions(source)
.iter()
.map(|region| {
let mut end = region.close;
if source[end..].starts_with('¶') {
end += '¶'.len_utf8();
}
if let Some((_, width)) = attribution_tag(&source[end..]) {
end += width;
}
region.open..end
})
.collect();
let closers = Closers::new(source);
for &(start, end) in closers.comments.iter().chain(&closers.highlights) {
ranges.push(start..end);
}
ranges.sort_by_key(|range| range.start);
ranges
}
const SEAM_PASSES: usize = 32;
fn merge_seam_levels(markdown: &str, accept: bool) -> String {
let mut merged = merge_across_marks(markdown, accept);
for _ in 0..SEAM_PASSES {
let next = merge_across_marks(&merged, accept);
if next == merged {
break;
}
merged = next;
}
merged
}
fn names_outer(note: &str) -> bool {
super::view_notes::nested_revision_tags(note).is_some_and(|tags| tags.len() > 1)
|| super::view_notes::nested_plain_revisions(note).is_some_and(|parts| parts.len() > 1)
}
pub(super) fn nested_change_regions(source: &str) -> Vec<Range<usize>> {
change_regions(source)
.iter()
.filter(|region| {
!escaped(source, region.close)
&& attribution_tag(&source[region.close..])
.is_some_and(|(note, _)| names_outer(note))
})
.map(|region| region.open..region.close)
.collect()
}
pub(crate) fn accept_clauses(markdown: &str) -> String {
resolve_with_policy(markdown, true, true)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum InlineKind {
Code,
Emphasis,
Strong,
Strike,
}
#[derive(Clone, Debug)]
struct InlineSpan {
kind: InlineKind,
range: Range<usize>,
inner_start: usize,
inner_end: usize,
content: Option<String>,
}
fn collect_inline_spans(source: &str) -> Vec<InlineSpan> {
let mut spans = Vec::new();
let mut stack: Vec<(InlineKind, usize)> = Vec::new();
for (event, range) in Parser::new_ext(source, parser_options()).into_offset_iter() {
match event {
Event::Code(content) => {
let bytes = source.as_bytes();
let inner_start = range.start
+ bytes[range.start..]
.iter()
.take_while(|&&b| b == b'`')
.count();
let inner_end = range.end
- bytes[range.start..range.end]
.iter()
.rev()
.take_while(|&&b| b == b'`')
.count();
spans.push(InlineSpan {
kind: InlineKind::Code,
range: range.clone(),
inner_start,
inner_end,
content: Some(content.into_string()),
});
}
Event::Start(Tag::Emphasis) => {
stack.push((InlineKind::Emphasis, range.start));
}
Event::Start(Tag::Strong) => {
stack.push((InlineKind::Strong, range.start));
}
Event::Start(Tag::Strikethrough) => {
stack.push((InlineKind::Strike, range.start));
}
Event::End(TagEnd::Emphasis)
| Event::End(TagEnd::Strong)
| Event::End(TagEnd::Strikethrough) => {
let kind = match event {
Event::End(TagEnd::Emphasis) => InlineKind::Emphasis,
Event::End(TagEnd::Strong) => InlineKind::Strong,
_ => InlineKind::Strike,
};
if let Some((k, start)) = stack.pop()
&& k == kind
{
let bytes = source.as_bytes();
let open_marker_len = bytes[start..]
.iter()
.take_while(|&&b| b == bytes[start])
.count();
let close_marker_len = bytes[..range.end]
.iter()
.rev()
.take_while(|&&b| b == bytes[start])
.count()
.min(open_marker_len);
spans.push(InlineSpan {
kind,
range: start..range.end,
inner_start: start + open_marker_len,
inner_end: range.end - close_marker_len,
content: None,
});
}
}
_ => {}
}
}
spans
}
fn body_contribution(source: &str, region: &ChangeRegion, accept: bool) -> String {
if let Some(mid) = region.split {
if accept {
return source[mid + 2..region.body.end].to_string();
}
return source[region.body.start..mid].to_string();
}
let kept = if accept {
region.inserted
} else {
!region.inserted
};
if kept {
source[region.body.clone()].to_string()
} else {
String::new()
}
}
fn outermost_spans(source: &str) -> Vec<InlineSpan> {
let mut spans = collect_inline_spans(source);
spans.sort_by(|a, b| {
a.range
.start
.cmp(&b.range.start)
.then(b.range.end.cmp(&a.range.end))
});
let mut outer: Vec<InlineSpan> = Vec::new();
for span in spans {
if let Some(prev) = outer.last_mut()
&& span.range.start < prev.range.end
{
if span.range == prev.range {
*prev = span;
}
continue;
}
outer.push(span);
}
outer
}
fn member_spans(source: &str) -> Vec<InlineSpan> {
let mut spans = collect_inline_spans(source);
spans.sort_by(|a, b| {
a.range
.start
.cmp(&b.range.start)
.then(b.range.end.cmp(&a.range.end))
});
let mut deduped: Vec<InlineSpan> = Vec::new();
for span in spans {
if let Some(prev) = deduped.last_mut()
&& prev.range == span.range
{
*prev = span;
continue;
}
deduped.push(span);
}
deduped
}
fn span_marker(text: &str, span: &InlineSpan) -> String {
match span.kind {
InlineKind::Strike => "~~".to_string(),
_ => {
let ch = text[span.range.start..].chars().next().unwrap_or('*');
let run = text[span.range.start..]
.chars()
.take_while(|&c| c == ch)
.count();
ch.to_string().repeat(run)
}
}
}
fn span_content(text: &str, span: &InlineSpan) -> String {
span.content
.clone()
.unwrap_or_else(|| text[span.inner_start..span.inner_end].to_string())
}
struct SeamSpan {
kind: InlineKind,
cover: Range<usize>,
content: String,
marker: String,
flipped: bool,
}
impl SeamSpan {
fn delimiter(&self) -> char {
self.marker.chars().next().unwrap_or('`')
}
}
fn contribution_span(source: &str, region: &ChangeRegion, accept: bool) -> Option<SeamSpan> {
let kept = body_contribution(source, region, accept);
if kept.is_empty() {
return None;
}
let spans = outermost_spans(&kept);
let [span] = spans.as_slice() else {
return None;
};
if span.range != (0..kept.len()) {
return None;
}
let tagged = attribution_tag(&source[region.close..])
.filter(|_| !escaped(source, region.close))
.map_or(region.close, |(_, width)| region.close + width);
Some(SeamSpan {
kind: span.kind,
cover: region.open..tagged,
content: span_content(&kept, span),
marker: span_marker(&kept, span),
flipped: false,
})
}
fn seam_breaks(source: &str, regions: &[ChangeRegion]) -> Vec<usize> {
let literal = Literal::new(source);
let mut regions = regions.iter().peekable();
let mut breaks = Vec::new();
for (at, _) in source.match_indices("\n\n") {
while regions.next_if(|r| r.close <= at).is_some() {}
let in_change = regions.peek().is_some_and(|r| r.open < at);
if !in_change && !literal.in_fence(at) && literal.verbatim_end(at).is_none() {
breaks.push(at);
}
}
breaks
}
fn edge_windows<'a>(
source: &'a str,
breaks: &[usize],
start: usize,
end: usize,
) -> (&'a str, &'a str) {
let before = breaks.partition_point(|&b| b + 2 <= start);
let from = before.checked_sub(1).map_or(0, |i| breaks[i] + 2);
let after = breaks.partition_point(|&b| b < end);
let to = breaks.get(after).copied().unwrap_or(source.len());
(&source[from..start], &source[end..to])
}
fn resolved_edge(text: &str, accept: bool, last: bool) -> Option<char> {
count_edge_bytes(text.len());
let resolved = resolve_with_policy(text, accept, false);
if last {
resolved.chars().last()
} else {
resolved.chars().next()
}
}
fn other_flavour(delimiter: char) -> Option<char> {
match delimiter {
'*' => Some('_'),
'_' => Some('*'),
_ => None,
}
}
fn flush_seam_spans(
source: &str,
breaks: &[usize],
accept: bool,
members: &mut [SeamSpan],
pending: &mut Vec<usize>,
splices: &mut Vec<(usize, usize, String)>,
) {
if pending.is_empty() {
return;
}
let group = std::mem::take(pending);
let start = members[group[0]].cover.start;
let end = members[*group.last().unwrap_or(&0)].cover.end;
let mut marker = members[group[0]].marker.clone();
let mut flipped = group.iter().any(|&i| members[i].flipped);
if marker.starts_with('_') {
let (before, after) = edge_windows(source, breaks, start, end);
let left = resolved_edge(before, accept, true);
let right = resolved_edge(after, accept, false);
if left.is_some_and(|c| c.is_alphanumeric()) || right.is_some_and(|c| c.is_alphanumeric()) {
marker = "*".repeat(marker.chars().count());
flipped = true;
}
}
if group.len() == 1 {
if flipped {
splices.push((
start,
end,
format!("{marker}{}{marker}", members[group[0]].content),
));
}
return;
}
let mut content = String::new();
for &i in &group {
content.push_str(&members[i].content);
}
let replacement = match members[group[0]].kind {
InlineKind::Code => {
let (open, close) = super::from_docx::ooxml::code_fence(&content);
format!("{open}{content}{close}")
}
_ => format!("{marker}{content}{marker}"),
};
splices.push((start, end, replacement));
}
fn merge_across_marks(source: &str, accept: bool) -> String {
let regions = change_regions(source);
if regions.is_empty() {
return source.to_string();
}
let breaks = seam_breaks(source, ®ions);
let mut members: Vec<SeamSpan> = Vec::new();
for span in member_spans(source) {
if regions
.iter()
.any(|r| r.open < span.range.start && span.range.end < r.close)
{
continue;
}
members.push(SeamSpan {
kind: span.kind,
cover: span.range.clone(),
content: span_content(source, &span),
marker: span_marker(source, &span),
flipped: false,
});
}
for region in ®ions {
if let Some(member) = contribution_span(source, region, accept) {
members.push(member);
}
}
if members.is_empty() {
return source.to_string();
}
members.sort_by(|a, b| {
a.cover
.start
.cmp(&b.cover.start)
.then(b.cover.end.cmp(&a.cover.end))
});
let mut children: Vec<Vec<usize>> = vec![Vec::new(); members.len()];
let mut top: Vec<usize> = Vec::new();
let mut stack: Vec<usize> = Vec::new();
for (i, member) in members.iter().enumerate() {
while stack
.last()
.is_some_and(|&p| member.cover.start >= members[p].cover.end)
{
stack.pop();
}
match stack.last() {
Some(&parent) => children[parent].push(i),
None => top.push(i),
}
if member.cover.start < member.cover.end {
stack.push(i);
}
}
fn seam_level(
source: &str,
breaks: &[usize],
accept: bool,
members: &mut [SeamSpan],
level: &[usize],
splices: &mut Vec<(usize, usize, String)>,
) {
let mut pending: Vec<usize> = Vec::new();
for &i in level {
if pending
.last()
.is_some_and(|&p| members[i].cover.start < members[p].cover.end)
{
continue;
}
let touching = pending.last().is_some_and(|&p| {
resolve_with_policy(
&source[members[p].cover.end..members[i].cover.start],
accept,
false,
)
.is_empty()
});
if touching {
let &last = pending.last().unwrap_or(&0);
if members[last].kind == members[i].kind
&& (members[i].kind == InlineKind::Code
|| members[last].marker == members[i].marker)
{
pending.push(i);
continue;
}
if members[i].delimiter() == members[last].delimiter()
&& let Some(alt) = other_flavour(members[i].delimiter())
{
members[i].marker = alt.to_string().repeat(members[i].marker.chars().count());
members[i].flipped = true;
}
}
flush_seam_spans(source, breaks, accept, members, &mut pending, splices);
pending.push(i);
}
flush_seam_spans(source, breaks, accept, members, &mut pending, splices);
}
let mut splices: Vec<(usize, usize, String)> = Vec::new();
for level in &children {
if level.len() > 1 {
seam_level(source, &breaks, accept, &mut members, level, &mut splices);
}
}
seam_level(source, &breaks, accept, &mut members, &top, &mut splices);
if splices.is_empty() {
return source.to_string();
}
splices.sort_by_key(|s| (s.0, std::cmp::Reverse(s.1)));
let mut kept: Vec<(usize, usize, String)> = Vec::new();
for splice in splices {
if kept
.iter()
.any(|&(start, end, _)| splice.0 < end && start < splice.1)
{
continue;
}
kept.push(splice);
}
kept.sort_by_key(|s| std::cmp::Reverse(s.0));
let mut result = source.to_string();
for (start, end, replacement) in kept {
result = format!("{}{}{}", &result[..start], replacement, &result[end..]);
}
result
}
pub(super) fn resolve_with_policy(
markdown: &str,
accept: bool,
remove_deleted_lines: bool,
) -> String {
#[derive(Clone, Copy, PartialEq, Eq)]
enum In {
Text,
Inserted,
Deleted,
Old,
New,
Comment,
}
let mut out = String::with_capacity(markdown.len());
let mut line_start = 0;
let mut visible_text = false;
let mut removed_text = false;
let mut dropped_line = false;
let mut outer: Vec<In> = Vec::new();
let mut state = In::Text;
let mut folded_at: Option<usize> = None;
let mut comment = String::new();
let mut paragraph_attribution = false;
let mut joining_separator: Option<usize> = None;
let mut strip_joined_heading = false;
let mut empty_inserted_heading = false;
let heading_prefix = |text: &str| {
let hashes = text.bytes().take_while(|&byte| byte == b'#').count();
let spaces = text[hashes..]
.bytes()
.take_while(|&byte| matches!(byte, b' ' | b'\t'))
.count();
((1..=6).contains(&hashes) && spaces > 0).then_some(hashes + spaces)
};
let list_prefix = |text: &str| {
let indent = text.bytes().take_while(|&b| b == b' ').take(4).count();
if indent > 3 {
return None;
}
let rest = &text[indent..];
let marker = if rest.starts_with(['-', '+', '*']) {
1
} else {
let digits = rest.bytes().take_while(u8::is_ascii_digit).take(10).count();
if !(1..=9).contains(&digits) || !rest[digits..].starts_with(['.', ')']) {
return None;
}
digits + 1
};
let spaces = rest[marker..]
.bytes()
.take_while(|&b| matches!(b, b' ' | b'\t'))
.count();
(spaces > 0).then_some(indent + marker + spaces)
};
Pieces::default().feed(&encode_spans_kept(markdown), |piece| match piece {
Piece::Text(text) => {
if state == In::Comment {
comment.push_str(text);
}
let shown = match state {
In::Text => true,
In::Inserted | In::New => accept,
In::Deleted | In::Old => !accept,
In::Comment => false,
};
if shown {
let mut text = text;
if let Some(mut consumed) = joining_separator {
while consumed < 2 {
if let Some(rest) = text
.strip_prefix("\r\n")
.or_else(|| text.strip_prefix('\n'))
{
text = rest;
consumed += 1;
} else {
break;
}
}
if consumed == 2 || !text.is_empty() {
joining_separator = None;
strip_joined_heading = consumed > 0;
} else {
joining_separator = Some(consumed);
}
}
if strip_joined_heading && !text.is_empty() {
if let Some(prefix) = heading_prefix(text).or_else(|| list_prefix(text)) {
text = &text[prefix..];
}
strip_joined_heading = false;
}
if !text.is_empty() {
empty_inserted_heading = false;
}
if state == In::Text {
folded_at = None;
}
if remove_deleted_lines {
for ch in text.chars() {
if ch == '\n' {
let empty_line = out.len() == line_start;
if removed_text && !visible_text {
out.truncate(line_start);
dropped_line = true;
} else if dropped_line
&& empty_line
&& (out.is_empty() || out.ends_with("\n\n"))
{
dropped_line = false;
} else {
out.push(ch);
dropped_line = false;
}
line_start = out.len();
visible_text = false;
removed_text = false;
} else {
out.push(ch);
visible_text |= !ch.is_whitespace();
}
}
} else {
out.push_str(text);
}
}
}
Piece::Token(token) => {
if remove_deleted_lines
&& state != In::Comment
&& matches!(token, Token::DeleteStart | Token::SubstituteStart)
{
removed_text = true;
}
let opened = match token {
Token::InsertStart
| Token::InsertEnd
| Token::DeleteStart
| Token::DeleteEnd
| Token::SubstituteStart
| Token::SubstituteSeparator
| Token::SubstituteEnd
if state == In::Comment =>
{
None
}
Token::MarkStart
| Token::MarkEnd
| Token::FieldStart
| Token::FieldSeparator
| Token::FieldEnd => {
let shown = match state {
In::Text => true,
In::Inserted | In::New => accept,
In::Deleted | In::Old => !accept,
In::Comment => false,
};
if shown {
out.push_str(delimiter(token));
folded_at = None;
}
None
}
Token::InsertStart | Token::DeleteStart => {
folded_at = Some(out.len());
match token {
Token::InsertStart => Some(In::Inserted),
_ => Some(In::Deleted),
}
}
Token::SubstituteStart => {
folded_at = Some(out.len());
Some(In::Old)
}
Token::CommentStart | Token::AttributionStart => Some(In::Comment),
Token::ParagraphInsertion => {
paragraph_attribution = true;
folded_at = None;
if !accept {
let start = out.rfind('\n').map_or(0, |at| at + 1);
let line = &out[start..];
empty_inserted_heading = heading_prefix(line) == Some(line.len());
if empty_inserted_heading {
out.truncate(start);
}
}
Some(In::Comment)
}
Token::HighlightStart => Some(state),
Token::SubstituteSeparator => {
if accept {
folded_at = None;
}
state = In::New;
None
}
Token::HighlightEnd
| Token::InsertEnd
| Token::DeleteEnd
| Token::SubstituteEnd => {
state = outer.pop().unwrap_or(In::Text);
None
}
Token::CommentBreak => None,
Token::CommentEnd | Token::AttributionEnd => {
state = outer.pop().unwrap_or(In::Text);
if std::mem::take(&mut paragraph_attribution) && !accept {
joining_separator = Some(0);
strip_joined_heading = false;
}
if state == In::Text
&& let Some(at) = folded_at.take()
&& token == Token::AttributionEnd
&& names_outer(&comment)
{
out.truncate(at);
line_start = out.rfind('\n').map_or(0, |at| at + 1);
visible_text = false;
dropped_line = false;
}
comment.clear();
None
}
};
if let Some(opened) = opened {
outer.push(state);
state = opened;
}
}
});
if remove_deleted_lines && removed_text && !visible_text {
out.truncate(line_start);
}
if empty_inserted_heading {
out.truncate(out.trim_end_matches('\n').len());
}
out
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod tests {
use super::*;
#[test]
fn underscore_seam_edges_resolve_only_their_own_paragraph() {
let para = "word _a_{++_b_++} tail\n\n";
let source = para.repeat(300);
EDGE_BYTES.with(|count| count.set(0));
let resolved = resolve(&source, true);
assert_eq!(resolved, "word _ab_ tail\n\n".repeat(300));
let bytes = EDGE_BYTES.with(std::cell::Cell::get);
assert!(
bytes < 4 * source.len(),
"{bytes} bytes resolved for a {}-byte source",
source.len()
);
}
#[test]
fn an_underscore_seam_edge_is_read_across_a_change_holding_a_blank_line() {
let source = "{++x\n\ny++}_a_{++_b_++}z\n\nnext";
assert_eq!(resolve(source, true), "x\n\ny*ab*z\n\nnext");
}
fn pieces(encoded: &str) -> Vec<String> {
let mut out = Vec::new();
Pieces::default().feed(encoded, |piece| {
out.push(match piece {
Piece::Text(text) => text.to_string(),
Piece::Token(token) => format!("<{token:?}>"),
});
});
out
}
#[test]
fn a_field_crosses_paragraphs_only_from_a_paragraph_start() {
for (line, opens) in [
("{TOC}", true),
(" {TOC}", true),
("## {TOC}", true),
("- {TOC}", true),
("> 1. {TOC}", true),
("12) {TOC}", true),
("See {TOC}", false),
("#x {TOC}", false),
("1.{TOC}", false),
] {
let source = format!("<!-- p0 -->\n{line}a\n\nb{{/}}\n");
let at = source.find("{TOC").unwrap();
assert_eq!(opens_paragraph(&source, at), opens, "{line}");
let ends = field_ends(&source, &Literal::new(&source));
assert_eq!(ends.contains_key(&at), opens, "{line}");
}
let source = "{TOC}a {PAGE}1{/}\n\nb{/}";
let ends = field_ends(source, &Literal::new(source));
assert_eq!(ends.get(&0), Some(&(source.len() - 3)));
let source = "{TOC}a\n\n```\nx\n```\n\nb{/}";
assert!(field_ends(source, &Literal::new(source)).is_empty());
}
#[test]
fn every_span_kind_is_encoded() {
assert_eq!(
pieces(&encode("a{++b++}c{--d--}e{~~f~>g~~}h{==i==}{>>j<<}")),
[
"a",
"<InsertStart>",
"b",
"<InsertEnd>",
"c",
"<DeleteStart>",
"d",
"<DeleteEnd>",
"e",
"<SubstituteStart>",
"f",
"<SubstituteSeparator>",
"g",
"<SubstituteEnd>",
"h",
"<HighlightStart>",
"i",
"<HighlightEnd>",
"<CommentStart>",
"j",
"<CommentEnd>",
]
);
}
#[test]
fn incomplete_or_escaped_delimiters_stay_text() {
for source in [
"a {++ b",
"a ++} b",
"{~~no separator~~}",
r"\{++not a change++}",
"{--}",
] {
assert_eq!(encode(source), source, "{source}");
}
assert_ne!(encode(r"\\{++x++}"), r"\\{++x++}");
}
#[test]
fn an_escaped_closer_or_separator_is_text_inside_the_span() {
assert_eq!(
pieces(&encode(r"{++a \++} b++}")),
["<InsertStart>", r"a \++} b", "<InsertEnd>"]
);
assert_eq!(
pieces(&encode(r"{~~a\~>b~>c~~}")),
[
"<SubstituteStart>",
r"a\~>b",
"<SubstituteSeparator>",
"c",
"<SubstituteEnd>"
]
);
assert_eq!(
pieces(&encode(r"{>>x \<<} y<<}")),
["<CommentStart>", r"x \<<} y", "<CommentEnd>"]
);
assert_eq!(encode(r"{++a \++}"), r"{++a \++}");
assert_eq!(encode(r"{~~a\~>b~~}"), r"{~~a\~>b~~}");
assert_eq!(
pieces(&encode(r"{++a\\++} b++}")),
["<InsertStart>", r"a\\", "<InsertEnd>", " b++}"]
);
assert_eq!(resolve(r"{++a \++} b++}", true), r"a \++} b");
assert_eq!(resolve(r"{++a \++} b++}", false), "");
}
#[test]
fn indented_code_is_verbatim_not_a_fence() {
for hand in [
" ```\n a{\\++b\n ```\n",
" ```\n x++\\}y\n ```\n",
" a{++b++}c\n",
"\tcode {++x++} too\n",
] {
assert_eq!(encode(hand), hand, "{hand:?}");
}
}
#[test]
fn an_escape_from_a_code_block_unwinds_inside_its_fence_only() {
for (document, written) in [
("fenced {++x++} code", r"fenced {\++x++\} code"),
(r"{\++x++}", r"{\\\++x++\}"),
("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"$x_{--}$ and ",
r"$x_{\--}$ and ",
),
] {
let fence = format!("```\n{written}\n```\n");
assert_eq!(encode(&fence), format!("```\n{document}\n```\n"));
let text = format!("a {written} b");
assert_eq!(encode(&text), text, "outside a fence it is Markdown's");
}
for hand in [
r"C:\\path\\x",
r"\\d+",
r"a\\b",
r"\\\\",
r"even {\\++ odd and \{++ text",
r"close ++\\} and sep ~\\>",
] {
let fence = format!("```\n{hand}\n```\n");
assert_eq!(encode(&fence), fence, "{hand}");
}
assert_eq!(
pieces(&encode("```\nkeep {++new++} old\n```\n")),
[
"```\nkeep ",
"<InsertStart>",
"new",
"<InsertEnd>",
" old\n```\n"
]
);
assert_eq!(
pieces(&encode("```\nold\\{++new++}\n```\n")),
[
"```\nold\\",
"<InsertStart>",
"new",
"<InsertEnd>",
"\n```\n"
]
);
assert_eq!(
pieces(&encode("```\n{++new\\++}\n```\n")),
["```\n", "<InsertStart>", "new\\", "<InsertEnd>", "\n```\n"]
);
assert_eq!(
pieces(&encode("```\n{~~old\\~>new~~}\n```\n")),
[
"```\n",
"<SubstituteStart>",
"old\\",
"<SubstituteSeparator>",
"new",
"<SubstituteEnd>",
"\n```\n"
]
);
assert_eq!(
pieces(&encode("```\n{~~a~\\>c~>b~~}\n```\n")),
[
"```\n",
"<SubstituteStart>",
"a~>c",
"<SubstituteSeparator>",
"b",
"<SubstituteEnd>",
"\n```\n"
]
);
assert_eq!(
encode("---\ntitle: a~\\>b\n---\n"),
"---\ntitle: a~\\>b\n---\n"
);
}
fn encode_counted(source: &str) -> (String, usize) {
CLOSER_STEPS.with(|steps| steps.set(0));
let out = encode(source);
(out, CLOSER_STEPS.with(|steps| steps.get()))
}
#[test]
fn unclosed_openers_encode_in_linear_time() {
let source = "{++ {-- {~~ {== {>> ~> ".repeat(40_000);
let (out, steps) = encode_counted(&source);
assert_eq!(out, source);
assert!(
steps <= 16 * source.len(),
"{steps} closer-search steps for {} bytes: an opener rescans the text",
source.len()
);
}
#[test]
fn unclosed_links_fields_and_highlights_encode_in_linear_time() {
for source in [
"[a](b".repeat(6_000),
"{PAGE}a ".repeat(6_000),
format!("{}{{/}}", "{PAGE}a ".repeat(6_000)),
"==a ".repeat(6_000),
] {
let (_, steps) = encode_counted(&source);
assert!(
steps <= 16 * source.len(),
"{source:.12}: {steps} closer-search steps for {} bytes: a search rescans its line or paragraph",
source.len()
);
}
}
#[test]
fn spans_cross_paragraphs_and_changes_do_not_nest() {
assert_eq!(
pieces(&encode("A{++\n\nB {--c--}++}")),
["A", "<InsertStart>", "\n\nB {--c--}", "<InsertEnd>"]
);
}
#[test]
fn a_highlight_holds_changes_and_comments() {
assert_eq!(
pieces(&encode("{==a {++b++}{>>Ana<<} {~~c~>d~~}==}{>>note<<}")),
[
"<HighlightStart>",
"a ",
"<InsertStart>",
"b",
"<InsertEnd>",
"<CommentStart>",
"Ana",
"<CommentEnd>",
" ",
"<SubstituteStart>",
"c",
"<SubstituteSeparator>",
"d",
"<SubstituteEnd>",
"<HighlightEnd>",
"<CommentStart>",
"note",
"<CommentEnd>",
]
);
assert_eq!(
pieces(&encode("{==a {==b==} {++c==}")),
["<HighlightStart>", "a {==b", "<HighlightEnd>", " {++c==}"]
);
assert_eq!(resolve("{==a{++b++}{--c--}==}{>>n<<}", true), "ab");
assert_eq!(resolve("{==a{++b++}{--c--}==}{>>n<<}", false), "ac");
}
#[test]
fn a_mark_run_closes_past_a_wide_first_character() {
assert_eq!(
pieces(&encode("==é== and ==→x==")),
[
"<MarkStart>",
"é",
"<MarkEnd>",
" and ",
"<MarkStart>",
"→x",
"<MarkEnd>"
]
);
}
#[test]
fn a_change_holds_highlights_and_comments_one_level_deep() {
assert_eq!(
pieces(&encode("{~~a~>{==b==}{>>n<<}~~}")),
[
"<SubstituteStart>",
"a",
"<SubstituteSeparator>",
"<HighlightStart>",
"b",
"<HighlightEnd>",
"<CommentStart>",
"n",
"<CommentEnd>",
"<SubstituteEnd>",
]
);
assert_eq!(
pieces(&encode("{++a {--b--}++}")),
["<InsertStart>", "a {--b--}", "<InsertEnd>"]
);
assert_eq!(
pieces(&encode("{++{==a {--b--}==}++}")),
[
"<InsertStart>",
"<HighlightStart>",
"a {--b--}",
"<HighlightEnd>",
"<InsertEnd>"
]
);
assert_eq!(
pieces(&encode("{>>a {++b++}<<}")),
[
"<CommentStart>",
"a ",
"<InsertStart>",
"b",
"<InsertEnd>",
"<CommentEnd>"
]
);
assert_eq!(resolve("{>>a {++b++}<<}", true), "");
assert_eq!(
accept_clauses("one\n\n{>>see {--x--}<<}\n\ntwo"),
accept_clauses("one\n\n{>>see x<<}\n\ntwo")
);
assert_eq!(resolve("{==x==}{>>see {++this++}<<}", true), "x");
let text = "x{++a{>>n<<}b++}{~~c~>{==d==}{>>m<<}e~~}";
assert_eq!(resolve(text, true), "xabde");
assert_eq!(resolve(text, false), "xc");
}
#[test]
fn a_complete_comment_inside_a_change_is_opaque_to_its_boundaries() {
let text = "{~~a{>>x ~> y<<} b~>c~~}";
assert_eq!(
pieces(&encode(text)),
[
"<SubstituteStart>",
"a",
"<CommentStart>",
"x ~> y",
"<CommentEnd>",
" b",
"<SubstituteSeparator>",
"c",
"<SubstituteEnd>",
]
);
assert_eq!(resolve(text, true), "c");
assert_eq!(resolve(text, false), "a b");
for payload in ["~>", "++}", "--}", "~~}", "==}"] {
let text = format!("{{++a{{>>{payload}<<}}b++}}");
assert_eq!(
pieces(&encode(&text)),
[
"<InsertStart>",
"a",
"<CommentStart>",
payload,
"<CommentEnd>",
"b",
"<InsertEnd>"
],
"insertion {payload:?}",
);
assert_eq!(resolve(&text, true), "ab", "insertion {payload:?} accept");
assert_eq!(resolve(&text, false), "", "insertion {payload:?} reject");
let text = format!("{{--a{{>>{payload}<<}}b--}}");
assert_eq!(
pieces(&encode(&text)),
[
"<DeleteStart>",
"a",
"<CommentStart>",
payload,
"<CommentEnd>",
"b",
"<DeleteEnd>"
],
"deletion {payload:?}",
);
assert_eq!(resolve(&text, true), "", "deletion {payload:?} accept");
assert_eq!(resolve(&text, false), "ab", "deletion {payload:?} reject");
let text = format!("{{~~a{{>>{payload}<<}} b~>c~~}}");
assert_eq!(
pieces(&encode(&text)),
[
"<SubstituteStart>",
"a",
"<CommentStart>",
payload,
"<CommentEnd>",
" b",
"<SubstituteSeparator>",
"c",
"<SubstituteEnd>",
],
"substitution-old {payload:?}",
);
assert_eq!(resolve(&text, true), "c", "sub-old {payload:?} accept");
assert_eq!(resolve(&text, false), "a b", "sub-old {payload:?} reject");
let text = format!("{{~~a~>b{{>>{payload}<<}} c~~}}");
assert_eq!(
pieces(&encode(&text)),
[
"<SubstituteStart>",
"a",
"<SubstituteSeparator>",
"b",
"<CommentStart>",
payload,
"<CommentEnd>",
" c",
"<SubstituteEnd>",
],
"substitution-new {payload:?}",
);
assert_eq!(resolve(&text, true), "b c", "sub-new {payload:?} accept");
assert_eq!(resolve(&text, false), "a", "sub-new {payload:?} reject");
let text = format!("{{==a{{>>{payload}<<}}b==}}");
assert_eq!(
pieces(&encode(&text)),
[
"<HighlightStart>",
"a",
"<CommentStart>",
payload,
"<CommentEnd>",
"b",
"<HighlightEnd>",
],
"highlight {payload:?}",
);
assert_eq!(resolve(&text, true), "ab", "highlight {payload:?} accept");
assert_eq!(resolve(&text, false), "ab", "highlight {payload:?} reject");
}
}
#[test]
fn incomplete_comments_and_escaped_comment_openers_do_not_break_changes() {
let text = "{++a{>>b++} c";
assert_eq!(
pieces(&encode(text)),
["<InsertStart>", "a{>>b", "<InsertEnd>", " c"]
);
assert_eq!(resolve(text, true), "a{>>b c");
assert_eq!(resolve(text, false), " c");
let text = r"\{++a{>>b++} c++}";
assert_eq!(encode(text), text);
assert_eq!(resolve(text, true), text);
assert_eq!(resolve(text, false), text);
let text = "before `{>>a++}` text after\n";
assert_eq!(encode(text), text);
assert_eq!(resolve(text, true), text);
assert_eq!(resolve(text, false), text);
}
#[test]
fn many_failed_openers_with_comments_stay_linear() {
let failed = "{~~x".repeat(2_000);
let comment = "{>>payload ~~} ~> body<<} ".repeat(2_000);
let source = format!("{failed}{comment}");
let (output, steps) = encode_counted(&source);
assert!(
steps <= 16 * source.len(),
"{steps} closer-search steps for {} bytes: an opener rescans the comments",
source.len()
);
assert!(output.contains("~>"));
assert!(output.contains("payload"));
}
#[test]
fn highlight_openers_before_comment_held_closers_stay_linear() {
let openers = "{==".repeat(20_000);
let comments = "{>>x==}y<<} ".repeat(20_000);
let source = format!("{openers}{comments}");
let (output, steps) = encode_counted(&source);
assert!(
steps <= 16 * source.len(),
"{steps} closer-search steps for {} bytes: the pairing pass re-skips the comments per opener",
source.len()
);
assert!(output.contains("==}"));
assert!(output.contains('y'));
}
#[test]
fn a_footnote_label_goes_before_a_change_that_opens_its_line() {
assert_eq!(
pieces(&encode(
"x\n{++[^2]: Added.++}\n{--[^a]:\tGone--} {++[^b]: y++}"
)),
[
"x\n[^2]: ",
"<InsertStart>",
"Added.",
"<InsertEnd>",
"\n[^a]:\t",
"<DeleteStart>",
"Gone",
"<DeleteEnd>",
" ",
"<InsertStart>",
"[^b]: y",
"<InsertEnd>",
]
);
for text in [
"{++[^]: a++}",
"{++[^a b]: c++}",
"{++[^a] b++}",
"{>>[^a]: b<<}",
] {
assert!(!pieces(&encode(text))[0].starts_with("[^"), "{text}");
}
assert_eq!(resolve("a\n{++[^2]: b++}\n", false), "a\n\n");
}
#[test]
fn stand_in_characters_in_the_source_come_back_unchanged() {
let source = "odd \u{2E0E} and \u{F0000} {++\u{2E0F}++}";
let encoded = encode(source);
assert_eq!(
pieces(&encoded),
[
"odd ",
"\u{2E0E} and ",
"\u{F0000} ",
"<InsertStart>",
"\u{2E0F}",
"<InsertEnd>"
]
);
assert_eq!(
decode(&encode("plain \u{2E0E} text")),
"plain \u{2E0E} text"
);
}
#[test]
fn resolving_keeps_one_side() {
let text = "a{++b++}c{--d--}e{~~f~>g~~}h{==i==}{>>j<<}k \\{++l++}";
assert_eq!(resolve(text, true), "abcegh".to_string() + "ik \\{++l++}");
assert_eq!(resolve(text, false), "acdefh".to_string() + "ik \\{++l++}");
}
#[test]
fn resolve_joins_two_code_spans_touching_after_a_mark() {
assert_eq!(
resolve("Use `alpha`{++`beta`++} here.", true),
"Use `alphabeta` here.",
);
assert_eq!(
resolve("Use `alpha`{++x++}`beta` here.", false),
"Use `alphabeta` here.",
);
assert_eq!(
resolve("Use `a`{~~`b`~>`c`~~}`d` here.", true),
"Use `acd` here.",
);
assert_eq!(
resolve("Use `a`{~~`b`~>`c`~~}`d` here.", false),
"Use `abd` here.",
);
assert_eq!(
resolve("Use `a`{~~x~>`c`~~}`d` here.", true),
"Use `acd` here.",
);
assert_eq!(
resolve("Use `alpha`{++```++} here.", true),
"Use `alpha`\\`\\`\\` here.",
);
assert_eq!(
resolve("Use alpha{++beta++}gamma.", true),
"Use alphabetagamma.",
);
assert_eq!(
resolve("Use alpha {++beta++} gamma.", true),
"Use alpha beta gamma.",
);
assert_eq!(
resolve("Use alpha{++beta++}gamma.", false),
"Use alphagamma.",
);
}
#[test]
fn resolve_joins_emphasis_touching_after_a_mark() {
for marker in ["*", "_"] {
let markdown = format!("Say {marker}a{marker}{{--x--}}{marker}b{marker} now.");
let joined = resolve(&markdown, true);
assert_eq!(joined, format!("Say {marker}ab{marker} now."), "{joined:?}");
let kept = resolve(&markdown, false);
assert_eq!(kept, "Say *a*x*b* now.", "{kept:?}");
}
let joined = resolve("Say **a**{--x--}**b** now.", true);
assert_eq!(joined, "Say **ab** now.");
let kept = resolve("Say **a**{--x--}**b** now.", false);
assert_eq!(kept, "Say **a**x**b** now.");
let joined = resolve("Use ~~a~~{--x--}~~b~~ here.", true);
assert_eq!(joined, "Use ~~ab~~ here.");
assert_eq!(resolve("Say *a*{--x--}b* now.", false), "Say *a*xb* now.");
}
#[test]
fn resolve_keeps_a_shorter_emphasis_run_out_of_a_triple_star_join() {
let joined = resolve("***a***{--x--}*b*", true);
assert_eq!(joined, "***a***_b_", "{joined:?}");
let bolded = collect_inline_spans(&joined)
.into_iter()
.any(|span| span.kind == InlineKind::Strong && span.range.end > 7);
assert!(!bolded, "the second span came back bold: {joined:?}");
let joined = resolve("**a**{--x--}*b*", true);
assert_eq!(joined, "**a**_b_", "{joined:?}");
}
#[test]
fn resolve_keeps_an_inner_join_inside_a_joined_container() {
let joined = resolve("**A `b`{--x--}`c` D**{--y--}**E**", true);
assert_eq!(joined, "**A `bc` DE**", "{joined:?}");
let joined = resolve("**A *b*{--x--}*c* D**{--y--}**E**", true);
assert_eq!(joined, "**A *bc* DE**", "{joined:?}");
let joined = resolve("*`a`{--x--}`b`*", true);
assert_eq!(joined, "*`ab`*", "{joined:?}");
}
#[test]
fn resolve_does_not_leave_an_attribution_tag_in_front_of_a_joined_span() {
let joined = resolve("*a*{++*b*++}{r5 @AC}", true);
assert_eq!(joined, "*ab*", "{joined:?}");
let joined = resolve("*a*{++*b*++}{r5 @AC}*c*", true);
assert_eq!(joined, "*abc*", "{joined:?}");
let kept = resolve("*a*{++*b*++}{r5 @AC}", false);
assert_eq!(kept, "*a*", "{kept:?}");
let literal = resolve("*a*{++*b*++}\\{r5 @AC}", true);
assert_eq!(literal, "*ab*\\{r5 @AC}", "{literal:?}");
}
#[test]
fn resolve_keeps_two_links_separate_with_a_mark_between() {
let kept = resolve("[a](u){--x--}[b](u)", false);
assert_eq!(kept, "[a](u)x[b](u)");
let dropped = resolve("[a](u){--x--}[b](u)", true);
assert_eq!(dropped, "[a](u)[b](u)");
}
#[test]
fn resolve_tolerates_a_partially_overlapping_seam() {
let source = "Say ___yd[ch](u)_____**u**[dsa](u)__t~~unv~~__{~~[`q`~~pkf~~g](u)*k*``sjg``~>__`k`**l**__~~} now.\n";
for accept in [true, false] {
let resolved = resolve(source, accept);
assert!(!resolved.is_empty(), "accept={accept}");
assert!(resolved.contains('S'), "{resolved:?}");
}
}
#[test]
fn resolving_keeps_a_fence_s_escapes() {
let fence = "```\nfenced {\\++x++\\} code\n```\n";
assert_eq!(resolve(fence, true), fence);
assert_eq!(resolve(fence, false), fence);
}
#[test]
fn rejecting_inserted_paragraph_marks_joins_only_the_following_separator() {
for (source, accepted, rejected) in [
("A¶{r1 @A}\n\nB", "A\n\nB", "AB"),
("A¶{r1 @A}\n\n B", "A\n\n B", "A B"),
("A¶{r1 @A}\n\n\n\nB", "A\n\n\n\nB", "A\n\nB"),
("A¶{r1 @A}\n\n{--B--}{r2 @A}C", "A\n\nC", "ABC"),
] {
assert_eq!(resolve(source, true), accepted, "accept {source:?}");
assert_eq!(resolve(source, false), rejected, "reject {source:?}");
}
}
#[test]
fn rejecting_a_whole_inserted_heading_leaves_no_empty_heading_prefix() {
for (source, accepted, rejected) in [
(
"Before.\n\n## {++Heading++}{r1 @A}¶{r2 @A}\n\nAfter.",
"Before.\n\n## Heading\n\nAfter.",
"Before.\n\nAfter.",
),
(
"Before.¶{r0 @A}\n\n## {++Heading++}{r1 @A}¶{r2 @A}\n\nAfter.",
"Before.\n\n## Heading\n\nAfter.",
"Before.After.",
),
(
"Before.\n\n## {++Heading++}{r1 @A}¶{r2 @A}",
"Before.\n\n## Heading",
"Before.",
),
] {
assert_eq!(resolve(source, true), accepted, "accept {source:?}");
assert_eq!(resolve(source, false), rejected, "reject {source:?}");
}
}
#[test]
fn resolving_literal_or_commented_paragraph_marks_keeps_real_boundaries() {
for accept in [true, false] {
let literal = "A¶\\{r1 @A}\n\nB";
assert_eq!(resolve(literal, accept), literal);
assert_eq!(resolve("A{>>¶{r1 @A}<<}\n\nB", accept), "A\n\nB");
}
}
#[test]
fn accepting_a_whole_deleted_paragraph_collapses_its_blank_separator() {
assert_eq!(
accept_clauses("Para A\n\n{--Para B--}\n\nPara C\n"),
"Para A\n\nPara C\n"
);
assert_eq!(
accept_clauses("Para A\n\n{--Para B--}\n\n{--Para D--}\n\nPara C\n"),
"Para A\n\nPara C\n"
);
assert_eq!(
accept_clauses("Para A\n\nPara B\n\nPara C\n"),
"Para A\n\nPara B\n\nPara C\n"
);
}
#[test]
fn an_escape_split_across_two_texts_is_carried() {
let encoded = encode("x\u{2E0E}y");
let split = encoded.char_indices().nth(2).map(|(i, _)| i).unwrap();
let mut splitter = Pieces::default();
let mut out = Vec::new();
for part in [&encoded[..split], &encoded[split..]] {
splitter.feed(part, |piece| {
if let Piece::Text(text) = piece {
out.push(text.to_string());
}
});
}
assert_eq!(out.concat(), "x\u{2E0E}y");
}
#[test]
fn every_comment_hides_its_own_delimiters() {
let text = "x {>>one<<} {~~a{>>y ~> z<<}b~>c~~} d{>>two<<}e";
assert_eq!(
pieces(&encode(text)),
[
"x ",
"<CommentStart>",
"one",
"<CommentEnd>",
" ",
"<SubstituteStart>",
"a",
"<CommentStart>",
"y ~> z",
"<CommentEnd>",
"b",
"<SubstituteSeparator>",
"c",
"<SubstituteEnd>",
" d",
"<CommentStart>",
"two",
"<CommentEnd>",
"e",
]
);
assert_eq!(resolve(text, true), "x c de");
assert_eq!(resolve(text, false), "x ab de");
let text = "{++a{>>x++}y\n\n<<}z++}";
assert_eq!(
pieces(&encode(text)),
[
"<InsertStart>",
"a",
"<CommentStart>",
"x++}y",
"<CommentBreak>",
"<CommentEnd>",
"z",
"<InsertEnd>",
]
);
assert_eq!(resolve(text, true), "az");
assert_eq!(resolve(text, false), "");
}
#[test]
fn a_complete_highlight_inside_a_change_is_opaque_to_its_boundaries() {
let text = "{~~a{==x ~> y==} b~>c~~}";
assert_eq!(
pieces(&encode(text)),
[
"<SubstituteStart>",
"a",
"<HighlightStart>",
"x ~> y",
"<HighlightEnd>",
" b",
"<SubstituteSeparator>",
"c",
"<SubstituteEnd>",
]
);
assert_eq!(resolve(text, true), "c");
assert_eq!(resolve(text, false), "ax ~> y b");
let text = "{++a{==b ++}c==}d++}";
assert_eq!(
pieces(&encode(text)),
[
"<InsertStart>",
"a",
"<HighlightStart>",
"b ++}c",
"<HighlightEnd>",
"d",
"<InsertEnd>",
]
);
assert_eq!(resolve(text, true), "ab ++}cd");
assert_eq!(resolve(text, false), "");
let text = "{==a{>>x==}y<<}b==}{>>done<<}";
assert_eq!(
pieces(&encode(text)),
[
"<HighlightStart>",
"a",
"<CommentStart>",
"x==}y",
"<CommentEnd>",
"b",
"<HighlightEnd>",
"<CommentStart>",
"done",
"<CommentEnd>",
]
);
let text = "{++a{==x++}y++}";
assert_eq!(
pieces(&encode(text)),
["<InsertStart>", "a{==x", "<InsertEnd>", "y++}"]
);
}
#[test]
fn a_blank_line_inside_a_comment_is_a_comment_paragraph_break() {
let text = "a{>>first\n\nsecond<<}b";
assert_eq!(
pieces(&encode(text)),
[
"a",
"<CommentStart>",
"first",
"<CommentBreak>",
"second",
"<CommentEnd>",
"b",
]
);
assert_eq!(
pieces(&encode("a{>>first\nsecond<<}b")),
["a", "<CommentStart>", "first\nsecond", "<CommentEnd>", "b"]
);
assert_eq!(
pieces(&encode("a{>>first\n\n\n \n\nsecond<<}b")),
[
"a",
"<CommentStart>",
"first",
"<CommentBreak>",
"second",
"<CommentEnd>",
"b",
]
);
assert_eq!(decode(&encode("a{>>first\n\nsecond<<}b")), "afirst secondb");
}
#[test]
fn malformed_critic_markup_is_text_with_a_warning() {
let (encoded, warnings) = encode_checked("{>>x ++} ~> y<<}");
assert_eq!(
encoded,
format!(
"{}{}{}",
stand_in(Token::CommentStart),
"x ++} ~> y",
stand_in(Token::CommentEnd)
)
);
assert!(warnings.is_empty(), "{warnings:?}");
let source = "`{++x ++}` {>>y ++}<<}";
let (encoded, warnings) = encode_checked(source);
assert!(encoded.starts_with("`{++x ++}` "), "{encoded}");
assert!(warnings.is_empty(), "{warnings:?}");
let cases = [
("{++a", "'{++' without its '++}'"),
("a ++} b", "'++}' with nothing open"),
("{~~a~~}", "'{~~' without its '~>' separator"),
("{>>a", "'{>>' without its '<<}'"),
];
for (source, warning) in cases {
let (encoded, warnings) = encode_checked(source);
assert_eq!(encoded, source, "{source}");
assert!(
warnings.iter().any(|w| w.contains(warning)),
"{source}: {warnings:?} lacks {warning:?}"
);
}
let (encoded, warnings) = encode_checked("{++a--}");
assert_eq!(encoded, "{++a--}");
assert!(warnings.iter().any(|w| w.contains("'{++'")), "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("'--}'")), "{warnings:?}");
}
#[test]
fn character_references_naming_stand_ins_stay_literal() {
for (text, guarded) in [
("a ⸎x⸏ b", 2),
("a ⸎x⸏ b", 2),
("a ⸎x b", 1),
("{>>a ⸙ b<<}", 1),
("a 󰀀 b", 1),
] {
let encoded = encode(text);
assert_eq!(
encoded.chars().filter(|&c| c == ESCAPE).count(),
guarded,
"{text}: {encoded:?}"
);
assert_eq!(restore(&encoded), text, "{text}");
}
for text in [
"a A b",
"a ˠ b",
"a � b",
r"a \⸎ b",
"`⸎`",
"```
⸎
```
",
] {
assert_eq!(encode(text), text, "{text}");
}
}
#[test]
fn a_closer_inside_a_complete_highlight_is_the_highlight_s_text() {
for text in [
"{==b++}c==}",
"{++a{==b++}c==}d++}",
"{~~a{==b~~}c==}d~>e~~}",
"{==a{>>x==}y<<}b==}",
] {
let (encoded, warnings) = encode_checked(text);
assert!(warnings.is_empty(), "{text}: {warnings:?} in {encoded:?}");
}
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod branch_tests {
use super::*;
type Case = (
&'static str,
&'static str,
&'static str,
&'static str,
&'static [&'static str],
Option<&'static str>,
);
#[test]
fn markup_resolves_warns_and_refuses_old_attributions() {
let cases: &[Case] = &[
(
"\\{++a++} b",
"\\{++a++} b",
"\\{++a++} b",
"\\{++a++} b",
&[],
None,
),
("\\\\{++a++} b", "\\\\a b", "\\\\ b", "\\\\a b", &[], None),
("{==a {++b++}==}{>>note<<}", "a b", "a ", "a b", &[], None),
("{~~a~>{==b==}{>>n<<}~~}", "b", "a", "b", &[], None),
(
"{++a{>>b++}c++}",
"a{>>bc++}",
"c++}",
"a{>>bc++}",
&[
"'++}' with nothing open on line 1 is text",
"'{>>' without its '<<}' on line 1 is text",
],
None,
),
("{~~a{>>x ~> y<<} b~>c~~}", "c", "a b", "c", &[], None),
(
"{++a {==b++} c==}",
"{++a b++} c",
"{++a b++} c",
"{++a b++} c",
&["'{++' without its '++}' on line 1 is text"],
None,
),
(
"{==a{>>b==}c<<}",
"{==a",
"{==a",
"{==a",
&["'{==' without its '==}' on line 1 is text"],
None,
),
(
"{++[^2]: Added later.++}",
"[^2]: Added later.",
"",
"[^2]: Added later.",
&[],
None,
),
(
"{++\n```\ncode\n```\n++}",
"\n```\ncode\n```\n",
"",
"\n```\ncode\n```\n",
&[],
None,
),
(
"a⸎b {++⸎++} {>>󰀀<<} &#;x � � &#xZZ; a; A",
"a⸎b ⸎ &#;x � � &#xZZ; a; A",
"a⸎b &#;x � � &#xZZ; a; A",
"a⸎b ⸎ &#;x � � &#xZZ; a; A",
&[],
None,
),
("a{>>one\n\ntwo<<}", "a", "a", "a", &[], None),
(
"{DATE \\@ \"MMMM d\"}March{/} and {PAGE} and \\{PAGE} and {++{PAGE}1{/}++}",
"{DATE \\\\\\@ \\\"MMMM d\\\"}March{/} and {PAGE} and \\{PAGE} and {PAGE}1{/}",
"{DATE \\\\\\@ \\\"MMMM d\\\"}March{/} and {PAGE} and \\{PAGE} and ",
"{DATE \\\\\\@ \\\"MMMM d\\\"}March{/} and {PAGE} and \\{PAGE} and {PAGE}1{/}",
&[],
None,
),
(
"<http://a{++b++}> [x](a{++b++}) <!-- {++x++} --> `{++x++}`",
"<http://a{++b++}> [x](a{++b++}) <!-- x --> `{++x++}`",
"<http://a{++b++}> [x](a{++b++}) <!-- --> `{++x++}`",
"<http://a{++b++}> [x](a{++b++}) <!-- x --> `{++x++}`",
&[],
None,
),
(
"[l]: http://x{++y++}\n\ntext",
"[l]: http://x{++y++}\n\ntext",
"[l]: http://x{++y++}\n\ntext",
"[l]: http://x{++y++}\n\ntext",
&[],
None,
),
(
" {++x++}",
" {++x++}",
" {++x++}",
" {++x++}",
&[],
None,
),
(
"{++a++}{r1 @A} b ¶{r3 @A}\n\nnext",
"a b \n\nnext",
" b next",
"a b \n\nnext",
&[],
None,
),
(
"{++a++}{r1 @A move m1} {--b--}{r2 @A move}",
"a ",
" b",
"a ",
&[],
None,
),
(
"==x== {==y==} a == b === c ==d=",
"==x== y a == b === c ==d=",
"==x== y a == b === c ==d=",
"==x== y a == b === c ==d=",
&[],
None,
),
(
"1. {--x--}\n10. y\n 1. z\n- {++w++}\n+ v",
"1. \n10. y\n 1. z\n- w\n+ v",
"1. x\n10. y\n 1. z\n- \n+ v",
"1. \n10. y\n 1. z\n- w\n+ v",
&[],
None,
),
(
"# {--Old heading--}\n\n## {++New++}\n\ntext",
"# \n\n## New\n\ntext",
"# Old heading\n\n## \n\ntext",
"# \n\n## New\n\ntext",
&[],
None,
),
(
"{~~old~>new~~} and {~~a~>~~} and {~~~>b~~}",
"new and and b",
"old and a and ",
"new and and b",
&[],
None,
),
("{++a\n\nb++}", "a\n\nb", "", "a\n\nb", &[], None),
("A{++\n\nB++}", "A\n\nB", "A", "A\n\nB", &[], None),
(
"{--line one\n\nline two--}\n\nkeep",
"\n\nkeep",
"line one\n\nline two\n\nkeep",
"keep",
&[],
None,
),
(
"{++unclosed and {--also",
"{++unclosed and {--also",
"{++unclosed and {--also",
"{++unclosed and {--also",
&[
"'{++' without its '++}' on line 1 is text",
"'{--' without its '--}' on line 1 is text",
],
None,
),
(
"closer only++} and --} and ~~} and ==} and <<}",
"closer only++} and --} and ~~} and ==} and <<}",
"closer only++} and --} and ~~} and ==} and <<}",
"closer only++} and --} and ~~} and ==} and <<}",
&[
"'++}' with nothing open on line 1 is text",
"'--}' with nothing open on line 1 is text",
"'<<}' with nothing open on line 1 is text",
"'==}' with nothing open on line 1 is text",
"'~~}' with nothing open on line 1 is text",
],
None,
),
(
"{>>comment only<<} and {==scope==}{>>c<<}{>>reply<<}",
" and scope",
" and scope",
" and scope",
&[],
None,
),
(
"{++x++}{>>r1 @ASR<<}",
"x",
"",
"x",
&[],
Some(
"line 1: old attribution `{>>r1 @ASR<<}` is no longer supported; write `{r1 @ASR}`. A comment with that text is written `{>>c1 @X: r1 @ASR<<}`.",
),
),
(
"{++**bold**++}*{>>r1 Alice (2026-10-01T09:00:00Z)<<}",
"**bold***",
"\\*",
"**bold***",
&[],
Some(
"line 1: old attribution `{>>r1 Alice (2026-10-01T09:00:00Z)<<}` is no longer supported; write `{r1 Alice (2026-10-01T09:00:00Z)}`. A comment with that text is written `{>>c1 @X: r1 @ASR<<}`.",
),
),
(
"{~~a~>b~~}{>>r1 @A on r0 @B<<}",
"b",
"a",
"b",
&[],
Some(
"line 1: old attribution `{>>r1 @A on r0 @B<<}` is no longer supported; write `{r1 @A re r0 @B}`. A comment with that text is written `{>>c1 @X: r1 @ASR<<}`.",
),
),
(
"{~~a~>b~~}{>>r1 Al (2026-10-01T09:00:00Z); r2 Bo (2026-10-01T09:00:00Z)<<}",
"b",
"a",
"b",
&[],
Some(
"line 1: old attribution `{>>r1 Al (2026-10-01T09:00:00Z); r2 Bo (2026-10-01T09:00:00Z)<<}` is no longer supported; write `{r1 Al (2026-10-01T09:00:00Z); r2 Bo (2026-10-01T09:00:00Z)}`. A comment with that text is written `{>>c1 @X: r1 @ASR<<}`.",
),
),
(
"{++a++}{>>header1.r3 @A<<}",
"a",
"",
"a",
&[],
Some(
"line 1: old attribution `{>>header1.r3 @A<<}` is no longer supported; write `{header1.r3 @A}`. A comment with that text is written `{>>c1 @X: r1 @ASR<<}`.",
),
),
("{++a++}{>>.r3 @A<<}", "a", "", "a", &[], None),
("{++a++}{>>he$d.r3 @A<<}", "a", "", "a", &[], None),
("{++a++}{>>r1+ @A<<}", "a", "", "a", &[], None),
(
"{++a++}{>>r1 @A",
"a{>>r1 @A",
"{>>r1 @A",
"a{>>r1 @A",
&["'{>>' without its '<<}' on line 1 is text"],
None,
),
(
"| {++a++} | b |\n|---|---|\n| {--c--} | d |",
"| a | b |\n|---|---|\n| | d |",
"| | b |\n|---|---|\n| c | d |",
"| a | b |\n|---|---|\n| | d |",
&[],
None,
),
(
"> {++quoted++}\n> more",
"> quoted\n> more",
"> \n> more",
"> quoted\n> more",
&[],
None,
),
("*a{++*b*++}c*", "*abc*", "*ac*", "*a*b*c*", &[], None),
("_a{--_b_--}c_", "_ac_", "_abc_", "_ac_", &[], None),
(
"**a{++b++}c** and __x{--y--}z__",
"**abc** and __xz__",
"**ac** and __xyz__",
"**abc** and __xz__",
&[],
None,
),
(
"{++a~~b~~c++} and {--`code`--}",
"a~~b~~c and ",
" and `code`",
"a~~b~~c and ",
&[],
None,
),
(
"text {++inserted++}{r5+6 @AC}¶{r5+6 @AC}\n\nnext para",
"text inserted\n\nnext para",
"text next para",
"text inserted\n\nnext para",
&[],
None,
),
("x{--y--}{r1 @A re r0 @B}z", "xz", "xz", "xz", &[], None),
(
"{++the ++}{r13 @RC}{--applicable--}{r16 @TL re r13 @RC}{++ law++}{r13 @RC}",
"the law",
"",
"the law",
&[],
None,
),
(
"{--30 days--}{r50 @TL}{++45 days++}{r60 @RC}",
"45 days",
"30 days",
"45 days",
&[],
None,
),
(
"{~~30 days~>45 days~~}{r50 @TL; r60 @RC}",
"45 days",
"30 days",
"45 days",
&[],
None,
),
];
for &(source, accepted, rejected, clauses, warnings, legacy) in cases {
assert_eq!(resolve(source, true), accepted, "accept {source:?}");
assert_eq!(resolve(source, false), rejected, "reject {source:?}");
assert_eq!(accept_clauses(source), clauses, "clauses {source:?}");
assert_eq!(encode_checked(source).1, warnings, "warnings {source:?}");
assert_eq!(
legacy_attribution_error(source).as_deref(),
legacy,
"legacy {source:?}"
);
}
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod scanner_branch_tests {
use super::*;
#[test]
fn comment_closers_count_nesting_and_skip_escapes() {
let s = "a{>>b<<}c<<}";
assert_eq!(comment_closer(s, "{>>", "<<}", 0, s.len()), Some(9));
let s = "\\<<}é<<}";
assert_eq!(comment_closer(s, "{>>", "<<}", 0, s.len()), Some(6));
let s = "\\{>>x<<}";
assert_eq!(comment_closer(s, "{>>", "<<}", 0, s.len()), Some(5));
assert_eq!(comment_closer("abc<<}", "{>>", "<<}", 0, 3), None);
assert_eq!(comment_closer("abc", "{>>", "<<}", 0, 3), None);
}
#[test]
fn separators_sit_at_depth_one_only() {
let s = "a~>b";
assert_eq!(
comment_separator(s, "{~~", "~~}", "~>", 0, s.len()),
Some(1)
);
let s = "{~~c~>d~~}é~>e";
assert_eq!(
comment_separator(s, "{~~", "~~}", "~>", 0, s.len()),
Some(12)
);
let s = "abc~~}~>";
assert_eq!(comment_separator(s, "{~~", "~~}", "~>", 0, s.len()), None);
let s = "a\\~>b\\~~}c~>";
assert_eq!(
comment_separator(s, "{~~", "~~}", "~>", 0, s.len()),
Some(10)
);
assert_eq!(comment_separator("abc", "{~~", "~~}", "~>", 0, 3), None);
}
#[test]
fn definitions_comments_autolinks_and_fence_escapes_read_their_shapes() {
assert_eq!(definition_destination("[a]: x"), Some(4));
assert_eq!(definition_destination(" [a\\]]: x"), Some(9));
assert_eq!(definition_destination("[]: x"), None);
assert_eq!(definition_destination("[a] x"), None);
assert_eq!(definition_destination("[a[b]: x"), None);
assert_eq!(definition_destination(" [a]: x"), None);
assert_eq!(definition_destination("[^1]: x"), None);
assert_eq!(definition_destination("[open"), None);
assert_eq!(comment_end("<!-- x --> y", 0), Some(10));
assert_eq!(comment_end("<!-- open", 0), None);
assert_eq!(comment_end("<b>", 0), None);
assert_eq!(autolink_end("<https://a.example> x", 0), Some(19));
assert_eq!(autolink_end("<https://a b>", 0), None);
assert_eq!(autolink_end("<https://a<b>", 0), None);
assert_eq!(autolink_end("<https://open", 0), None);
assert_eq!(autolink_end("<h:x>", 0), None);
assert_eq!(autolink_end("<mailto x>", 0), None);
assert_eq!(
fence_escape_at("\\{r1 @A}", 0),
Some(("{r1 @A}".to_string(), 8))
);
assert_eq!(
fence_escape_at("\\\\{r1 @A}", 0),
Some(("\\\\{r1 @A}".to_string(), 9))
);
assert_eq!(fence_escape_at("plain", 0), None);
}
}