use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use pulldown_cmark::{
Alignment, CodeBlockKind, Event, HeadingLevel, LinkType, Options, Parser, Tag, TagEnd,
};
use unicode_properties::{GeneralCategory, GeneralCategoryGroup, UnicodeGeneralCategory};
use super::critic::{self, Piece, Pieces, Token};
use super::diff::{continues, marker_len, opens_amount, table_row, table_row_change};
use super::xml::{
Change, Comment, Content, Document, FormatMark, Indent, Item, Kind, Label, LabelUse, Link,
List, Note, Paragraph, Picture, Run, RunFormat, StyleChangeKind, TableFormats, TextBox,
};
use super::{DocxOptions, MarkdownError, PageSize, TrackChanges, WrittenDocx, package};
use super::{math, view_notes, view_stories, view_styles};
pub fn markdown_to_docx(
markdown: &str,
options: &DocxOptions<'_>,
) -> Result<WrittenDocx, MarkdownError> {
if options.critic
&& let Some(error) = critic::legacy_attribution_error(markdown)
{
return Err(MarkdownError::Package(error));
}
let defaults = view_notes::file_defaults(markdown);
let mut own = options.clone();
if let Some(author) = defaults.author.filter(|_| !options.author_fixed) {
own.author = author;
}
if let Some(date) = defaults.date.clone().filter(|_| !options.date_fixed) {
own.date = date;
}
let options = &own;
if !is_date(&options.date) {
return Err(MarkdownError::Package(format!(
"date {:?} is no timestamp such as 2026-10-01T09:00:00Z",
options.date
)));
}
let document = read(markdown, options);
if let Some(error) = document
.revision_note_error
.as_ref()
.or(document.box_error.as_ref())
{
return Err(MarkdownError::Package(error.clone()));
}
let mut warnings = document.warnings.clone();
if let Some((key, value)) = defaults.unread.filter(|_| defaults.date.is_none()) {
warnings.push(format!(
"{key}: {value} is no timestamp (YYYY-MM-DDTHH:MM:SSZ or YYYY-MM-DD): \
undated comments and changes keep the default date"
));
}
if options.reference.is_some() && options.page != PageSize::default() {
warnings.push(format!(
"page size {} ignored: the reference document's page setup is used",
options.page.as_str()
));
}
let docx = package::assemble(&document, options, markdown, &mut warnings)?;
let docx = match options.track_changes {
_ if !options.critic => docx,
TrackChanges::All => docx,
TrackChanges::Accept => crate::document_comparer::accept_revisions(&docx)
.map_err(|e| MarkdownError::Package(e.to_string()))?,
TrackChanges::Reject => crate::document_comparer::reject_revisions(&docx)
.map_err(|e| MarkdownError::Package(e.to_string()))?,
};
let docx = match options.tracking.or(document.tracking) {
Some(on) => crate::settings::apply_settings_to_docx(
&docx,
&crate::settings::SettingsRequest {
track_revisions: Some(on),
..Default::default()
},
)
.map_err(MarkdownError::Package)?,
None => docx,
};
let docx = if options.scholar {
crate::settings::no_stretched_line_breaks(&docx).map_err(MarkdownError::Package)?
} else {
docx
};
Ok(WrittenDocx { docx, warnings })
}
pub(super) fn read(markdown: &str, options: &DocxOptions<'_>) -> Document {
let scholarly;
let markdown = if options.scholar {
let stories = options.reference.is_some_and(super::package::has_stories);
scholarly = scholar(markdown, stories);
scholarly.as_str()
} else {
markdown
};
let (source, critic_warnings) = if options.critic {
critic::encode_checked(&block_changes(markdown))
} else {
(markdown.to_string(), Vec::new())
};
let source = page_commands(&source);
let source = inline_math(table_pipes(&source), options.critic);
let mut writer = Writer::new(options);
(writer.box_markdown, writer.document.box_error) = text_box_sources(markdown);
writer.tables = table_plans(&source);
writer.note_breaks = note_breaks(&source);
writer.item_levels = item_levels(&source);
writer.label_definitions = label_definitions(&source);
let parser = Parser::new_ext(&source, parser_options());
writer.document.drawing_defs = parser
.reference_definitions()
.iter()
.map(|(name, def)| (name.to_string(), def.dest.to_string()))
.collect();
writer.document.drawing_backings = super::from_docx::drawing::backing_comments(&source);
let mut inserted_end: Option<usize> = None;
let newlines: Vec<usize> = source.match_indices('\n').map(|(at, _)| at).collect();
for (event, range) in parser.into_offset_iter() {
writer.source_line = newlines.partition_point(|&at| at < range.start) + 1;
if let Some(end) = inserted_end
&& range.start >= end
{
inserted_end = None;
let from = if source[..end].ends_with("\r\n") {
end - 2
} else if source[..end].ends_with('\n') {
end - 1
} else {
end
};
let gap = &source[from..range.start];
if gap.chars().all(char::is_whitespace) {
let extra = (gap.bytes().filter(|&b| b == b'\n').count() / 2).saturating_sub(1);
for _ in 0..extra {
writer.begin_paragraph();
writer.end_paragraph();
}
}
}
let ends_paragraph = matches!(&event, Event::End(TagEnd::Paragraph | TagEnd::Heading(_)));
writer.event(event);
if ends_paragraph
&& !writer.view
&& writer.target.is_none()
&& writer.cell.is_none()
&& writer.lists.is_empty()
&& writer.quote == 0
&& writer
.body
.iter()
.rev()
.find_map(|item| match item {
Item::Paragraph(paragraph) => Some(paragraph),
_ => None,
})
.is_some_and(|paragraph| {
paragraph.mark_fixed && paragraph.mark == Some(Kind::Insert)
})
{
inserted_end = Some(range.end);
}
}
let mut document = writer.finish();
document.warnings.splice(..0, critic_warnings);
document.index_wrapping_parents();
document
}
fn style_change_tag(raw: &str) -> (StyleChangeKind, &str, bool) {
match raw.split_once(' ') {
Some(("pPr", rest)) => (StyleChangeKind::Paragraph, rest, false),
Some(("rPr", rest)) => (StyleChangeKind::Run, rest, false),
Some(("other", rest)) => (StyleChangeKind::Other, rest, false),
_ => (StyleChangeKind::Run, raw, true),
}
}
fn inline_math(source: String, critic_on: bool) -> String {
inline_math_passes(source, critic_on).0
}
fn inline_math_passes(mut source: String, critic_on: bool) -> (String, usize) {
let mut passes = 0;
if !source.contains('$') {
return (source, passes);
}
let mut accepted = BTreeMap::new();
loop {
passes += 1;
let mut rejected = Vec::new();
for (event, range) in Parser::new_ext(&source, parser_options()).into_offset_iter() {
let (latex, display) = match event {
Event::InlineMath(latex) => (latex, false),
Event::DisplayMath(latex) => (latex, true),
_ => continue,
};
if accepted
.range(..=range.start)
.next_back()
.is_some_and(|(_, &end)| range.start < end)
{
continue;
}
let steals_formula = accepted.range(range.start..range.end).next().is_some();
let closer = range.end - 1;
if steals_formula
|| (!display && opens_amount(&source, closer))
|| (critic_on && critic::math_crosses_boundary(&latex))
{
rejected.push(range.start);
if display {
rejected.push(range.start + 1);
} else if opens_amount(&source, closer) {
let next = source[closer + 1..].trim_start_matches(|c: char| {
c.is_ascii_digit() || matches!(c, ',' | '.' | '-' | '–')
});
let protected = accepted
.range(..=closer)
.next_back()
.is_some_and(|(_, &end)| closer < end);
if !protected && opens_amount(next, 0) {
rejected.push(closer);
}
}
} else {
accepted.insert(range.start, range.end);
}
}
if rejected.is_empty() {
return (source, passes);
}
rejected.sort_unstable();
rejected.dedup();
accepted = accepted
.into_iter()
.map(|(start, end)| {
(
start + rejected.partition_point(|&at| at < start),
end + rejected.partition_point(|&at| at < end),
)
})
.collect();
let mut escaped = String::with_capacity(source.len() + rejected.len());
let mut from = 0;
for at in rejected {
escaped.push_str(&source[from..at]);
escaped.push('\\');
from = at;
}
escaped.push_str(&source[from..]);
source = escaped;
}
}
fn text_box_sources(markdown: &str) -> (HashMap<String, String>, Option<String>) {
let mut boxes = HashMap::new();
let mut seen = HashSet::new();
let mut open = None;
let mut error = None;
for (event, range) in Parser::new_ext(markdown, parser_options()).into_offset_iter() {
let (Event::Html(html) | Event::InlineHtml(html)) = event else {
continue;
};
let html = html.trim();
if let Some(name) = html
.strip_prefix("<!-- text-box ")
.and_then(|s| s.strip_suffix(" -->"))
{
if !seen.insert(name.to_string()) || open.is_some() {
error.get_or_insert_with(|| {
format!("text-box {name}: duplicate or overlapping marker region")
});
}
open = Some((name.to_string(), range.end));
} else if html == "<!-- /text-box -->"
&& let Some((name, start)) = open.take()
{
boxes.insert(
name,
markdown[start..range.start].trim().replace("<br>", "\n"),
);
}
}
(boxes, error)
}
fn block_changes(source: &str) -> String {
let regions = critic::change_regions(source);
let mut out = String::with_capacity(source.len());
let mut at = 0;
for region in regions {
out.push_str(&source[at..region.open]);
at = region.close;
let starts_line = region.open == 0 || source[..region.open].ends_with('\n');
let after = &source[region.close..];
let rewritten = if !starts_line {
None
} else if let Some(mid) = region.split {
substitution_blocks(
&source[region.body.start..mid],
&source[mid + "~>".len()..region.body.end],
after.is_empty() || after.starts_with('\n'),
)
} else {
let (open, close) = if region.inserted {
("{++", "++}")
} else {
("{--", "--}")
};
let ends_line = after.is_empty()
|| after.starts_with('\n')
|| source[..region.body.end].ends_with('\n');
let content = &source[region.body.clone()];
(ends_line && blocky(content))
.then(|| distribute(content, open, close))
.flatten()
};
match rewritten {
Some(text) => out.push_str(&text),
None => out.push_str(&source[region.open..region.close]),
}
}
out.push_str(&source[at..]);
out
}
fn substitution_blocks(old: &str, new: &str, ends_line: bool) -> Option<String> {
if !ends_line || !(blocky(old) || blocky(new)) {
return None;
}
let (old, new) = (distribute(old, "{--", "--}"), distribute(new, "{++", "++}"));
Some(format!("{}\n{}", old?, new?))
}
fn blocky(content: &str) -> bool {
content.lines().any(|line| {
let fenced = ["```", "~~~"]
.iter()
.any(|fence| line.trim_start().starts_with(fence));
fenced || marker_len(line) > 0 || table_row(line)
})
}
fn distribute(content: &str, open: &str, close: &str) -> Option<String> {
let lines: Vec<&str> = content.split('\n').collect();
let mut out = String::with_capacity(content.len());
let mut at = 0;
while at < lines.len() {
let line = lines[at];
if line.trim().is_empty() {
out.push_str(line);
at += 1;
} else if table_row(line) {
out.push_str(&table_row_change(line, open, close));
at += 1;
} else {
let marker = marker_len(line);
let length = if line.trim_start().starts_with('>') {
1 + lines[at + 1..]
.iter()
.take_while(|l| l.trim_start().starts_with('>'))
.count()
} else if line[..marker].contains('#') {
1
} else {
1 + lines[at + 1..].iter().take_while(|l| continues(l)).count()
};
if length == 1 && line[marker..].is_empty() {
return None;
}
out.push_str(&line[..marker]);
out.push_str(open);
out.push_str(&line[marker..]);
for block_line in &lines[at + 1..at + length] {
out.push('\n');
out.push_str(block_line);
}
out.push_str(close);
at += length;
}
if at < lines.len() {
out.push('\n');
}
}
Some(out)
}
const SCHOLAR_STYLES: [(&str, &str); 4] = [
(
"Normal",
"Latin Modern Roman 10pt, after 6pt, line 12pt exact, justify",
),
(
"\"#\"",
"Heading1, Latin Modern Roman bold 14.4pt, before 15pt, after 10pt, line 1, left, keep-next",
),
(
"\"##\"",
"Heading2, Latin Modern Roman bold 12pt, before 14pt, after 6.5pt, line 1, left, keep-next",
),
(
"\"###\"",
"Heading3, Latin Modern Roman bold 10pt, before 14pt, after 6.5pt, line 1, left, keep-next",
),
];
fn scholar(markdown: &str, stories: bool) -> String {
let (yaml, body) = split_front_matter(markdown).unwrap_or(("", markdown));
let mut lines: Vec<String> = yaml.lines().map(str::to_string).collect();
let mut named: Vec<String> = Vec::new();
let mut styles_at = None;
let mut headers = false;
let mut footers = false;
let mut page = false;
let mut block = "";
for (n, line) in lines.iter().enumerate() {
if !line.starts_with(' ') {
block = line.trim_end();
if block == "styles:" {
styles_at = Some(n);
}
continue;
}
let entry = view_styles::without_comment(line).trim();
let Some((key, _)) = entry.split_once(": ") else {
continue;
};
match block {
"styles:" => named.push(key.trim_matches('"').to_string()),
"headers:" => headers = true,
"footers:" => footers = true,
_ => {}
}
page |= matches!(block, "headers:" | "footers:") && line.contains("{PAGE");
}
let own_default = named.iter().any(|key| {
!key.bytes().all(|b| b == b'#') && !matches!(key.as_str(), "table" | "tables" | "changes")
});
let missing: Vec<String> = SCHOLAR_STYLES
.iter()
.filter(|(key, _)| {
let key = key.trim_matches('"');
if key == "Normal" {
!own_default
} else {
!named.iter().any(|n| n == key)
}
})
.map(|(key, value)| format!(" {key}: {value}"))
.collect();
match styles_at {
Some(at) => {
lines.splice(at + 1..at + 1, missing);
}
None if !missing.is_empty() => {
lines.push("styles:".to_string());
lines.extend(missing);
}
None => {}
}
if !footers && !page && !stories {
lines.push("footers:".to_string());
if !headers {
lines.push(" first: none".to_string());
}
lines.push(" default: {id: footer1, text: \"{PAGE}\", center}".to_string());
}
format!("---\n{}\n---\n\n{body}", lines.join("\n"))
}
#[doc(hidden)]
pub fn split_front_matter(markdown: &str) -> Option<(&str, &str)> {
let rest = markdown
.strip_prefix("---\n")
.or_else(|| markdown.strip_prefix("---\r\n"))?;
let mut at = 0;
for line in rest.split_inclusive('\n') {
if matches!(line.trim_end(), "---" | "...") {
return Some((&rest[..at], &rest[at + line.len()..]));
}
at += line.len();
}
None
}
pub(super) const PAGE_BREAK_LINE: &str = "<!-- page-break -->";
fn page_commands(source: &str) -> String {
const COMMANDS: [&str; 4] = [
r"\newpage",
r"\pagebreak",
r"\clearpage",
r"\cleardoublepage",
];
let mut out = String::with_capacity(source.len());
let mut fence: Option<&str> = None;
let mut front_matter = source.starts_with("---\n") || source.starts_with("---\r\n");
for (n, line) in source.split_inclusive('\n').enumerate() {
let bare = line.trim_end_matches(['\n', '\r']);
let trimmed = bare.trim();
if front_matter {
if n > 0 && (trimmed == "---" || trimmed == "...") {
front_matter = false;
}
out.push_str(line);
continue;
}
let indent = bare.len() - bare.trim_start().len();
if let Some(open) = fence {
if indent < 4
&& trimmed.starts_with(open)
&& trimmed.trim_start_matches(open).trim().is_empty()
{
fence = None;
}
out.push_str(line);
continue;
}
if indent < 4 && (trimmed.starts_with("```") || trimmed.starts_with("~~~")) {
fence = Some(&trimmed[..3]);
} else if indent < 4 && COMMANDS.contains(&trimmed) {
out.push_str(PAGE_BREAK_LINE);
out.push_str(&line[bare.len()..]);
if line.len() == bare.len() {
out.push('\n');
}
continue;
}
out.push_str(line);
}
out
}
fn table_pipes(source: &str) -> String {
let lines: Vec<&str> = source.split_inclusive('\n').collect();
let mut out = String::with_capacity(source.len());
let mut fence: Option<&str> = None;
let mut front_matter = source.starts_with("---\n") || source.starts_with("---\r\n");
let mut in_table = false;
for (n, line) in lines.iter().enumerate() {
let bare = line.trim_end_matches(['\n', '\r']);
let trimmed = bare.trim();
if front_matter {
if n > 0 && (trimmed == "---" || trimmed == "...") {
front_matter = false;
}
out.push_str(line);
continue;
}
let indent = bare.len() - bare.trim_start().len();
if let Some(open) = fence {
if indent < 4
&& trimmed.starts_with(open)
&& trimmed.trim_start_matches(open).trim().is_empty()
{
fence = None;
}
out.push_str(line);
continue;
}
if indent < 4 && (trimmed.starts_with("```") || trimmed.starts_with("~~~")) {
fence = Some(&trimmed[..3]);
in_table = false;
out.push_str(line);
continue;
}
let row =
indent < 4 && bare[..indent].bytes().all(|b| b == b' ') && trimmed.starts_with('|');
if !row {
in_table = false;
out.push_str(line);
continue;
}
let unshielded = unshield_pipes(bare);
if in_table {
out.push_str(&unshielded);
out.push_str(&line[bare.len()..]);
continue;
}
in_table = lines.get(n + 1).is_some_and(|next| {
let next = next.trim_end_matches(['\n', '\r']);
let indent = next.len() - next.trim_start().len();
indent < 4 && next[..indent].bytes().all(|b| b == b' ') && delimiter_row(next)
}) && row_columns(&unshielded)
== lines
.get(n + 1)
.map(|next| row_columns(next.trim_end_matches(['\n', '\r'])))
.unwrap_or(0);
out.push_str(if in_table { &unshielded } else { bare });
if in_table
&& !unshielded
.bytes()
.rev()
.take_while(|&b| b == b'\\')
.count()
.is_multiple_of(2)
{
out.push(' ');
}
out.push_str(&line[bare.len()..]);
}
out
}
fn unshield_pipes(line: &str) -> String {
let bytes = line.as_bytes();
let mut out = String::with_capacity(line.len());
let mut run = 0usize;
let mut at = 0usize;
while at < bytes.len() {
let rest = &line[at..];
let c = rest.chars().next().unwrap_or_default();
match c {
'\\' => {
run += 1;
out.push('\\');
at += 1;
}
'`' if run.is_multiple_of(2) => {
let ticks = rest.chars().take_while(|&c| c == '`').count();
let close = rest[ticks..]
.char_indices()
.find(|(i, _)| {
rest[ticks + i..].starts_with(&"`".repeat(ticks))
&& rest[ticks + i + ticks..]
.chars()
.next()
.is_none_or(|c| c != '`')
})
.map(|(i, _)| ticks + i + ticks);
let end = close.unwrap_or(ticks);
out.push_str(&rest[..end]);
at += end;
run = 0;
}
'$' if run.is_multiple_of(2) => {
let fence = usize::from(rest.starts_with("$$")) + 1;
let mut close = None;
let mut i = at + fence;
while i < bytes.len() {
let step = line[i..].chars().next().map_or(1, char::len_utf8);
match bytes[i] {
b'\\' => i += 1 + line[i + 1..].chars().next().map_or(1, char::len_utf8),
b'$' if line[i..].starts_with(&"$".repeat(fence)) => {
close = Some(i + fence);
break;
}
_ => i += step,
}
}
let end = close.unwrap_or(at + 1);
out.push_str(&line[at..end]);
at = end;
run = 0;
}
'<' if run.is_multiple_of(2)
&& rest
.chars()
.nth(1)
.is_some_and(|c| c.is_ascii_alphabetic() || c == '/') =>
{
let end = rest
.find('>')
.filter(|&close| html_tag(&rest[..=close]).is_some())
.map_or(1, |close| close + 1);
out.push_str(&rest[..end]);
at += end;
run = 0;
}
'|' => {
if run >= 2 && run.is_multiple_of(2) {
out.push(' ');
}
out.push('|');
at += 1;
run = 0;
}
_ => {
out.push(c);
at += c.len_utf8();
run = 0;
}
}
}
out
}
fn delimiter_row(line: &str) -> bool {
let line = line.trim();
let line = line.strip_prefix('|').unwrap_or(line);
let line = line.strip_suffix('|').unwrap_or(line);
line.split('|').all(|cell| {
let cell = cell.trim();
let cell = cell.strip_prefix(':').unwrap_or(cell);
let cell = cell.strip_suffix(':').unwrap_or(cell);
!cell.is_empty() && cell.bytes().all(|b| b == b'-')
})
}
fn row_columns(line: &str) -> usize {
let line = line.trim();
let bytes = line.as_bytes();
let (mut pipes, mut run, mut last_pipe) = (0usize, 0usize, None);
for (i, &b) in bytes.iter().enumerate() {
match b {
b'\\' => run += 1,
b'|' => {
if run.is_multiple_of(2) {
pipes += 1;
last_pipe = Some(i);
}
run = 0;
}
_ => run = 0,
}
}
if line.starts_with('|') {
pipes -= 1;
}
match last_pipe {
Some(i) if line[i + 1..].trim().is_empty() => pipes,
_ => pipes + 1,
}
}
#[derive(Clone, Debug, Default)]
struct TablePlan {
header_repeats: bool,
columns: Option<usize>,
align: Option<&'static str>,
rows: Vec<RowPlan>,
marks: HashMap<usize, Vec<(bool, view_notes::Tag)>>,
aligns: HashMap<usize, &'static str>,
style: Option<String>,
borders: Option<crate::markdown::borders::Sides>,
cell_borders: Vec<(view_notes::CellsAt, crate::markdown::borders::Sides)>,
row_borders: Vec<(usize, crate::markdown::borders::Sides)>,
styles: HashMap<usize, String>,
spacings: HashMap<usize, super::xml::Spacing>,
sizes: HashMap<usize, u32>,
geometry: super::xml::TableGeometry,
in_comment: bool,
fmt: Option<view_notes::Tag>,
grid_fmt: Option<u32>,
row_fmt: BTreeMap<usize, view_notes::Tag>,
cell_fmt: BTreeMap<(usize, usize), view_notes::Tag>,
para_fmt: HashMap<usize, Vec<view_notes::Tag>>,
row_marks: BTreeMap<usize, (bool, view_notes::Tag)>,
cell_marks: BTreeMap<(usize, usize), (view_notes::CellMark, view_notes::Tag)>,
mark_inherits: HashSet<usize>,
}
#[derive(Clone, Debug, Default)]
struct RowPlan {
breaks: bool,
first: Option<usize>,
cells: Vec<CellShape>,
pad: Vec<Pad>,
gaps: (usize, usize),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CellShape {
Cell { across: usize, merge: Option<bool> },
Spanned,
}
fn note_breaks(source: &str) -> Vec<(usize, usize)> {
let mut breaks = Vec::new();
let mut html = String::new();
let mut open: Option<(usize, usize)> = None;
for event in Parser::new_ext(source, parser_options()) {
match event {
Event::Start(Tag::HtmlBlock) => html.clear(),
Event::Html(text) => html.push_str(&text),
Event::Start(Tag::FootnoteDefinition(_)) => {
let counted = html
.lines()
.rev()
.find_map(view_notes::note_paragraphs)
.unwrap_or(0);
open = Some((counted, 0));
html.clear();
}
Event::End(TagEnd::FootnoteDefinition) => {
if let Some(counts) = open.take() {
breaks.push(counts);
}
}
Event::InlineHtml(text) if is_paragraph_break(&text) => {
if let Some((_, lines)) = &mut open {
*lines += 1;
}
}
Event::Start(_) if open.is_none() => html.clear(),
_ => {}
}
}
breaks
}
fn item_levels(source: &str) -> Vec<Option<u32>> {
let mut levels = Vec::new();
let mut open: Vec<(usize, usize)> = Vec::new();
let (mut lists, mut aside) = (0usize, 0usize);
for (event, range) in Parser::new_ext(source, parser_options()).into_offset_iter() {
let block = matches!(event, Event::Rule)
|| matches!(&event, Event::Start(tag) if !matches!(tag, Tag::List(_) | Tag::HtmlBlock));
if block && lists == 0 && aside == 0 {
open.clear();
}
match event {
Event::Start(Tag::List(_)) => lists += 1,
Event::End(TagEnd::List(_)) => lists -= 1,
Event::Start(Tag::BlockQuote(_) | Tag::FootnoteDefinition(_) | Tag::Table(_)) => {
aside += 1;
}
Event::End(TagEnd::BlockQuote(_) | TagEnd::FootnoteDefinition | TagEnd::Table) => {
aside -= 1;
}
Event::Start(Tag::Item) if aside > 0 => levels.push(None),
Event::Start(Tag::Item) => {
let (marker, text) = item_columns(source, range.start);
while open.last().is_some_and(|&(_, column)| marker < column) {
open.pop();
}
levels.push(u32::try_from(open.len()).ok().map(|level| level.min(8)));
open.push((marker, text));
}
_ => {}
}
}
levels
}
fn item_columns(source: &str, at: usize) -> (usize, usize) {
let start = source[..at].rfind('\n').map_or(0, |line| line + 1);
let end = source[at..]
.find('\n')
.map_or(source.len(), |line| at + line);
let mut column = 0;
let mut marker = None;
let mut chars = source[start..end].char_indices().peekable();
while let Some((offset, c)) = chars.next() {
let past = start + offset >= at;
match c {
'\t' => column += 4 - column % 4,
' ' => column += 1,
'-' | '*' | '+' if past => {
marker = Some(column);
column += 1;
break;
}
'0'..='9' if past => {
marker = Some(column);
column += 1;
while chars.next_if(|(_, c)| c.is_ascii_digit()).is_some() {
column += 1;
}
if chars.next_if(|(_, c)| matches!(c, '.' | ')')).is_some() {
column += 1;
}
break;
}
_ => column += 1,
}
}
let Some(marker) = marker else {
return (column, column);
};
let after = column;
for (_, c) in chars {
match c {
' ' => column += 1,
'\t' => column += 4 - column % 4,
_ => {
return (
marker,
if column - after > 4 {
after + 1
} else {
column
},
);
}
}
}
(marker, after + 1)
}
fn label_definitions(source: &str) -> HashMap<String, usize> {
let mut counts = HashMap::new();
for event in Parser::new_ext(source, parser_options()) {
if let Event::Start(Tag::FootnoteDefinition(label)) = event {
*counts.entry(note_label(&label)).or_insert(0) += 1;
}
}
counts
}
fn note_label(label: &str) -> String {
critic::decode(label).to_lowercase()
}
fn nth_label(label: &str, nth: usize) -> String {
if nth == 0 {
label.to_string()
} else {
format!("{label}\u{0}{nth}")
}
}
fn table_plans(source: &str) -> Vec<Option<TablePlan>> {
let mut plans = Vec::new();
let mut html = String::new();
let mut line = None;
let mut rows: Vec<(Vec<bool>, usize)> = Vec::new();
let mut in_cell = false;
for event in Parser::new_ext(source, parser_options()) {
match event {
Event::Start(Tag::HtmlBlock) => html.clear(),
Event::Html(text) => html.push_str(&text),
Event::Start(Tag::Table(_)) => {
line = html.lines().rev().find_map(view_notes::table_line);
html.clear();
rows.clear();
}
Event::Start(Tag::TableHead | Tag::TableRow) => rows.push((Vec::new(), 0)),
Event::Start(Tag::TableCell) => {
in_cell = true;
if let Some(row) = rows.last_mut() {
row.0.push(true);
}
}
Event::End(TagEnd::TableCell) => in_cell = false,
Event::End(TagEnd::Table) => {
plans.push(line.take().map(|line| plan_table(line, &rows)));
}
Event::Start(_) if !in_cell => html.clear(),
event if in_cell => {
if let Some(row) = rows.last_mut() {
if let Event::InlineHtml(text) = &event
&& is_paragraph_break(text)
{
row.1 += 1;
}
if let Some(empty) = row.0.last_mut() {
*empty = false;
}
}
}
_ => {}
}
}
plans
}
type Pad = (usize, Option<bool>);
fn plan_table(line: view_notes::TableLine, rows: &[(Vec<bool>, usize)]) -> TablePlan {
let mut merged_until: HashMap<usize, usize> = HashMap::new();
let mut shaped: Vec<(Vec<CellShape>, usize, Vec<Pad>)> = Vec::new();
let mut gaps: Vec<(usize, usize)> = Vec::new();
for (r, (cells, _)) in rows.iter().enumerate() {
let mut shapes = Vec::with_capacity(cells.len());
let (before, after) = line.gaps.get(&r).copied().unwrap_or((0, 0));
let lead = cells
.iter()
.take(before)
.take_while(|&&empty| empty)
.count();
let mut len = cells.len();
if let Some(columns) = line.columns {
while len > lead && before + (len - lead) > columns && cells[len - 1] {
len -= 1;
}
}
let tail = cells[..len]
.iter()
.skip(lead)
.rev()
.take(after)
.take_while(|&&empty| empty)
.count();
let (mut cell, mut column, mut spanned) = (0, before, 0);
for (at, &empty) in cells.iter().enumerate() {
if at < lead || at >= len - tail {
shapes.push(CellShape::Spanned);
continue;
}
if spanned > 0 && empty {
spanned -= 1;
shapes.push(CellShape::Spanned);
continue;
}
let (across, down) = line.merges.get(&(r, cell)).copied().unwrap_or((1, 1));
let merge = if down > 1 {
merged_until.insert(column, r + down - 1);
Some(true)
} else {
merged_until
.get(&column)
.is_some_and(|&until| until >= r)
.then_some(false)
};
shapes.push(CellShape::Cell { across, merge });
spanned = across - 1;
column += across;
cell += 1;
}
let end = line
.columns
.map_or(0, |columns| columns.saturating_sub(after.max(tail)));
let mut pad = Vec::new();
let mut at = cell;
while column < end {
let (across, down) = line.merges.get(&(r, at)).copied().unwrap_or((1, 1));
let across = across.max(1);
let merge = if down > 1 {
merged_until.insert(column, r + down - 1);
Some(true)
} else {
merged_until
.get(&column)
.is_some_and(|&until| until >= r)
.then_some(false)
};
pad.push((across, merge));
column += across;
at += 1;
}
shaped.push((shapes, cell, pad));
gaps.push((before, after.max(tail)));
}
let rows: Vec<RowPlan> = match (&line.row_paragraphs, line.one_per_cell) {
(_, Some(first)) => {
let mut at = first;
shaped
.into_iter()
.map(|(cells, count, pad)| {
at = at.saturating_add(count + pad.len());
RowPlan {
breaks: false,
first: Some(at - count - pad.len()),
cells,
pad,
gaps: (0, 0),
}
})
.collect()
}
(Some(counts), None) if counts.len() == rows.len() => counts
.iter()
.zip(rows)
.zip(shaped)
.map(|((&(first, n), &(_, breaks)), (cells, count, pad))| {
let mut pad = pad;
if breaks == 0 {
while count + pad.len() < n {
pad.push((1, None));
}
}
let pad = if count + pad.len() + breaks == n {
pad
} else {
Vec::new()
};
let exact = count + pad.len() + breaks == n;
RowPlan {
breaks: exact && breaks > 0,
first: exact.then_some(first),
cells,
pad,
gaps: (0, 0),
}
})
.collect(),
_ => shaped
.into_iter()
.map(|(cells, _, _)| RowPlan {
cells,
..RowPlan::default()
})
.collect(),
};
let rows: Vec<RowPlan> = rows
.into_iter()
.zip(gaps.into_iter().chain(std::iter::repeat((0, 0))))
.map(|(row, gaps)| RowPlan { gaps, ..row })
.collect();
TablePlan {
header_repeats: line.header_repeats,
columns: line.columns,
align: line.align,
rows,
marks: line.marks,
aligns: line.aligns,
styles: line.styles,
spacings: line.spacings,
sizes: line.sizes,
geometry: line.geometry,
style: line.style,
borders: line.borders,
cell_borders: line.cell_borders,
row_borders: line.row_borders,
in_comment: line.in_comment,
fmt: line.fmt,
grid_fmt: line.grid_fmt,
row_fmt: line.row_fmt,
cell_fmt: line.cell_fmt,
para_fmt: line.para_fmt,
row_marks: line.row_marks,
cell_marks: line.cell_marks,
mark_inherits: line.mark_inherits,
}
}
fn has_comment(text: &str) -> bool {
text.contains("{>>")
}
fn is_paragraph_break(html: &str) -> bool {
html_tag(html).is_some_and(|tag| !tag.closing && !tag.empty && tag.name == "br")
}
fn html_attribute(html: &str, name: &str) -> Option<String> {
let lower = html.to_ascii_lowercase();
let mut from = 0;
while let Some(found) = lower[from..].find(name) {
let at = from + found;
from = at + name.len();
let before = lower[..at].chars().next_back();
if !before.is_some_and(char::is_whitespace) {
continue;
}
let Some(value) = html[from..].trim_start().strip_prefix('=') else {
continue;
};
let value = value.trim_start();
let raw = match value.chars().next() {
Some(quote @ ('"' | '\'')) => value[1..].split(quote).next()?,
_ => value
.split(|c: char| c.is_whitespace() || c == '>')
.next()?,
};
return Some(crate::util::decode_entities(raw));
}
None
}
fn is_symbol_tag(html: &str) -> bool {
html.starts_with('<')
&& html.ends_with("/>")
&& html.matches('<').count() == 1
&& html_tag(html).is_some_and(|tag| tag.name == "sym" && tag.empty && !tag.closing)
}
fn comments_only(html: &str) -> bool {
html.lines()
.map(str::trim)
.all(|line| line.is_empty() || (line.starts_with("<!--") && line.ends_with("-->")))
}
const HTML_BLOCKS: [&str; 39] = [
"address",
"article",
"aside",
"blockquote",
"br",
"caption",
"dd",
"details",
"div",
"dl",
"dt",
"fieldset",
"figcaption",
"figure",
"footer",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"header",
"hr",
"li",
"main",
"nav",
"ol",
"p",
"pre",
"section",
"summary",
"table",
"tbody",
"td",
"th",
"thead",
"tr",
"ul",
];
fn html_block_text(html: &str) -> (Option<String>, Vec<String>) {
let mut first = None;
let mut paragraphs = Vec::new();
let mut text = String::new();
let flush = |text: &mut String, paragraphs: &mut Vec<String>| {
let decoded = crate::util::decode_entities(text);
let words: Vec<&str> = decoded.split_whitespace().collect();
if !words.is_empty() {
paragraphs.push(words.join(" "));
}
text.clear();
};
let mut rest = html;
while let Some(lt) = rest.find('<') {
text.push_str(&rest[..lt]);
rest = &rest[lt..];
if let Some(comment) = rest.strip_prefix("<!--") {
rest = comment.find("-->").map_or("", |end| &comment[end + 3..]);
continue;
}
let Some(gt) = rest.find('>') else {
break;
};
let inner = rest[1..gt].trim();
rest = &rest[gt + 1..];
let name: String = inner
.trim_start_matches('/')
.chars()
.take_while(char::is_ascii_alphanumeric)
.collect::<String>()
.to_ascii_lowercase();
if name.is_empty() {
continue;
}
if first.is_none() {
first = Some(name.clone());
}
if (name == "script" || name == "style") && !inner.starts_with('/') && !inner.ends_with('/')
{
let close = format!("</{name}");
rest = rest
.to_ascii_lowercase()
.find(&close)
.and_then(|at| rest[at..].find('>').map(|gt| &rest[at + gt + 1..]))
.unwrap_or("");
continue;
}
if HTML_BLOCKS.contains(&name.as_str()) {
flush(&mut text, &mut paragraphs);
}
}
text.push_str(rest);
flush(&mut text, &mut paragraphs);
(first, paragraphs)
}
struct HtmlTag {
name: String,
closing: bool,
empty: bool,
}
fn html_is_page_break(html: &str) -> bool {
let compact: String = html
.chars()
.filter(|c| !c.is_whitespace())
.map(|c| c.to_ascii_lowercase())
.collect();
compact.contains("type=\"page\"") || compact.contains("type='page'")
}
fn html_tag(html: &str) -> Option<HtmlTag> {
let inner = html.trim().strip_prefix('<')?.strip_suffix('>')?.trim();
if inner.starts_with(['!', '?']) {
return None;
}
let (closing, inner) = match inner.strip_prefix('/') {
Some(rest) => (true, rest.trim_start()),
None => (false, inner),
};
let name: String = inner
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || *c == '-')
.collect::<String>()
.to_ascii_lowercase();
if !name.starts_with(|c: char| c.is_ascii_alphabetic()) {
return None;
}
Some(HtmlTag {
name,
closing,
empty: inner.ends_with('/'),
})
}
fn closes(token: Token) -> &'static [Token] {
match token {
Token::InsertEnd => &[Token::InsertStart],
Token::DeleteEnd => &[Token::DeleteStart],
Token::SubstituteEnd => &[Token::SubstituteStart],
Token::HighlightEnd => &[Token::HighlightStart],
Token::CommentEnd => &[Token::CommentStart],
Token::AttributionEnd => &[Token::AttributionStart, Token::ParagraphInsertion],
Token::MarkEnd => &[Token::MarkStart],
_ => &[],
}
}
fn loose_tokens(tokens: Vec<Token>) -> Vec<Token> {
let mut closed = vec![false; tokens.len()];
let mut open: Vec<(Token, usize)> = Vec::new();
for (at, token) in tokens.iter().enumerate() {
let closers = closes(*token);
if !closers.is_empty() {
if let Some(index) = open.iter().rposition(|(start, _)| closers.contains(start)) {
let (_, start) = open.remove(index);
closed[start] = true;
}
} else if matches!(
token,
Token::InsertStart
| Token::DeleteStart
| Token::SubstituteStart
| Token::HighlightStart
| Token::CommentStart
| Token::AttributionStart
| Token::ParagraphInsertion
| Token::MarkStart
) {
open.push((*token, at));
}
}
let mut loose = Vec::new();
let mut open: Vec<(Token, usize)> = Vec::new();
for (at, token) in tokens.into_iter().enumerate() {
let closers = closes(token);
if !closers.is_empty() {
if let Some(index) = open.iter().rposition(|(start, _)| closers.contains(start)) {
open.remove(index);
} else {
loose.push(token);
}
continue;
}
match token {
Token::SubstituteSeparator
if open.last().is_some_and(|&(start, opened)| {
start == Token::SubstituteStart && closed[opened]
}) => {}
Token::FieldStart | Token::FieldSeparator | Token::FieldEnd => {}
_ => {
if matches!(
token,
Token::InsertStart
| Token::DeleteStart
| Token::SubstituteStart
| Token::HighlightStart
| Token::CommentStart
| Token::AttributionStart
| Token::ParagraphInsertion
| Token::MarkStart
) {
open.push((token, at));
if !closed[at] {
loose.push(token);
}
} else {
loose.push(token);
}
}
}
}
loose
}
pub fn image_targets(markdown: &str) -> Vec<String> {
Parser::new_ext(markdown, parser_options())
.filter_map(|event| match event {
Event::Start(Tag::Image { dest_url, .. }) => Some(critic::decode(&dest_url)),
_ => None,
})
.collect()
}
pub(super) fn parser_options() -> Options {
Options::ENABLE_TABLES
| Options::ENABLE_FOOTNOTES
| Options::ENABLE_STRIKETHROUGH
| Options::ENABLE_SUPERSCRIPT
| Options::ENABLE_SUBSCRIPT
| Options::ENABLE_TASKLISTS
| Options::ENABLE_YAML_STYLE_METADATA_BLOCKS
| Options::ENABLE_MATH
}
fn hl_color_class(class: &str) -> Option<&'static str> {
let colour = class
.get(..3)
.filter(|prefix| prefix.eq_ignore_ascii_case("hl-"))
.map(|_| &class[3..])?;
crate::ooxml::HIGHLIGHTS
.iter()
.copied()
.find(|h| *h != "none" && h.eq_ignore_ascii_case(colour))
}
const HEADINGS: [&str; 6] = [
"Heading1", "Heading2", "Heading3", "Heading4", "Heading5", "Heading6",
];
const MAX_PICTURE_WIDTH: u64 = 5_943_600;
struct OpenList {
instance: usize,
level: u32,
paragraphs: u32,
}
#[derive(Clone, Copy)]
struct SpanStart {
serial: u32,
kind: Kind,
paragraph: u64,
at_start: bool,
runs_before: usize,
at_break: Option<usize>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum RowCells {
Empty,
Whole(Kind, u32),
Mixed,
}
#[derive(Clone, Copy)]
struct Anchor {
slot: usize,
group: Option<usize>,
serials: [Option<u32>; 2],
attributed: u8,
}
impl Anchor {
fn takes_attribution(&self) -> bool {
self.group.is_none()
&& self.serials[1].is_some()
&& (self.attributed == 0 || (self.attributed == 1 && self.serials[0].is_some()))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum PoolStory {
Body,
Footnotes,
Endnotes,
}
struct Writer<'o, 'a> {
options: &'o DocxOptions<'a>,
soft_break: bool,
held: Vec<critic::Token>,
body: Vec<Item>,
definitions: HashMap<String, Vec<Item>>,
shared_tags: Vec<(u32, u32)>,
pools: HashMap<(PoolStory, Vec<u32>), (usize, Vec<u32>)>,
endnotes: HashSet<String>,
endnote_next: bool,
references: Vec<(String, Option<(Kind, u32)>)>,
target: Option<String>,
note_clauses: HashMap<String, view_notes::IdLine>,
paragraph: Option<usize>,
paragraph_serial: u64,
paragraph_runs: usize,
heading: Option<usize>,
label_prefix: Option<String>,
view: bool,
resolved: bool,
html_block: Option<String>,
tables: Vec<Option<TablePlan>>,
table_plan: Option<TablePlan>,
table_count: usize,
row_number: usize,
row_breaks: bool,
note_breaks: Vec<(usize, usize)>,
item_levels: Vec<Option<u32>>,
item_count: usize,
label_definitions: HashMap<String, usize>,
label_defined: HashMap<String, usize>,
label_uses: HashMap<String, usize>,
note_count: usize,
note_paragraph_breaks: bool,
note_style_next: Vec<String>,
note_style: Vec<String>,
note_spacing_next: Vec<super::xml::Spacing>,
note_spacing: Vec<super::xml::Spacing>,
note_paragraph: usize,
cell_paragraph: Option<usize>,
row_shapes: Vec<CellShape>,
row_pad: Vec<Pad>,
row_before: usize,
spanned: bool,
quote: u32,
lists: Vec<OpenList>,
bullets: Option<usize>,
code_block: bool,
table: Option<Vec<Option<&'static str>>>,
column: usize,
cell: Option<Option<&'static str>>,
row: Option<(usize, Option<(Kind, u32)>)>,
row_cells: RowCells,
prefix_runs: Vec<usize>,
image: Option<(String, String, String, Vec<Token>)>,
drawing_block: Option<(String, String, String)>,
metadata: Option<String>,
source_line: usize,
box_markdown: HashMap<String, String>,
box_names: HashMap<String, usize>,
box_duplicates: HashSet<String>,
box_open: Option<(String, Option<String>, usize)>,
box_spans: Vec<(String, Option<String>, usize, usize)>,
bold: u32,
italic: u32,
strike: u32,
underline: u32,
superscript: u32,
subscript: u32,
mark: u32,
mark_color: Vec<&'static str>,
dropped_html: Vec<String>,
code: u32,
link: u32,
html_links: u32,
pieces: Pieces,
change: Option<(Kind, u32)>,
serial: u32,
guessed_wraps: Vec<(u32, Option<String>)>,
slot: usize,
span_start: Option<SpanStart>,
closed: Option<u32>,
substituted: Option<u32>,
substitution: Option<(usize, Option<usize>)>,
comment_anchor: Option<Anchor>,
attribution_open: bool,
paragraph_attribution: bool,
pending_scopes: Vec<(usize, usize)>,
range_end_at: Option<usize>,
shared_range: Option<usize>,
unplaced: HashMap<usize, Vec<(&'static str, view_notes::Tag)>>,
held_in: Vec<(u32, u32, Vec<u32>)>,
run_after_close: bool,
scope: Option<(usize, usize)>,
groups: usize,
anchor: Option<Anchor>,
comment: Option<Comment>,
field_code: Option<String>,
id_line: Option<view_notes::IdLine>,
paragraph_in_comments: Option<Vec<u32>>,
page_break_due: bool,
page_break_change: Option<(Kind, view_notes::Tag)>,
authors: HashMap<String, view_notes::Author>,
ranged: BTreeMap<String, Vec<u32>>,
ranged_comments: BTreeMap<String, Vec<u32>>,
range_ended: HashSet<String>,
document: Document,
}
fn peeled_note(note: &str) -> (String, Vec<Option<String>>) {
let peeled: Vec<(String, Option<String>)> = note.split(" re ").map(peel_move_part).collect();
let names: Vec<Option<String>> = peeled.iter().map(|(_, name)| name.clone()).collect();
if names.iter().all(Option::is_none) {
return (note.to_string(), names);
}
let joined = peeled
.iter()
.map(|(body, _)| body.as_str())
.collect::<Vec<_>>()
.join(" re ");
let parses = view_notes::nested_revision_tags(&joined).is_some()
|| view_notes::revision_tags(&joined).is_some()
|| view_notes::nested_plain_revisions(&joined).is_some()
|| view_notes::plain_revisions(&joined).is_some()
|| view_notes::plain_revision(&joined).is_some();
if parses {
(joined, names)
} else {
(note.to_string(), vec![None; names.len()])
}
}
fn peel_move_part(part: &str) -> (String, Option<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(), Some(decode_move_name(name)));
}
}
if let Some(body) = part.strip_suffix(" move") {
return (body.to_string(), Some(String::new()));
}
(part.to_string(), None)
}
fn decode_move_name(token: &str) -> String {
let mut out = String::with_capacity(token.len());
let mut rest = token;
while let Some(at) = rest.find('%') {
out.push_str(&rest[..at]);
match rest.get(at + 1..at + 3) {
Some("25") => out.push('%'),
Some("20") => out.push(' '),
_ => {
out.push('%');
rest = &rest[at + 1..];
continue;
}
}
rest = &rest[at + 3..];
}
out.push_str(rest);
out
}
impl<'o, 'a> Writer<'o, 'a> {
fn new(options: &'o DocxOptions<'a>) -> Self {
Self {
soft_break: false,
held: Vec::new(),
options,
body: Vec::new(),
definitions: HashMap::new(),
endnotes: HashSet::new(),
endnote_next: false,
shared_tags: Vec::new(),
pools: HashMap::new(),
references: Vec::new(),
target: None,
note_clauses: HashMap::new(),
paragraph: None,
paragraph_serial: 0,
paragraph_runs: 0,
heading: None,
label_prefix: None,
view: false,
resolved: false,
html_block: None,
tables: Vec::new(),
table_plan: None,
table_count: 0,
row_number: 0,
row_breaks: false,
note_breaks: Vec::new(),
item_levels: Vec::new(),
item_count: 0,
label_definitions: HashMap::new(),
label_defined: HashMap::new(),
label_uses: HashMap::new(),
note_count: 0,
note_paragraph_breaks: false,
note_style_next: Vec::new(),
note_style: Vec::new(),
note_spacing_next: Vec::new(),
note_spacing: Vec::new(),
note_paragraph: 0,
cell_paragraph: None,
row_shapes: Vec::new(),
row_pad: Vec::new(),
row_before: 0,
spanned: false,
quote: 0,
lists: Vec::new(),
bullets: None,
code_block: false,
table: None,
column: 0,
cell: None,
row: None,
row_cells: RowCells::Empty,
prefix_runs: Vec::new(),
image: None,
drawing_block: None,
metadata: None,
source_line: 1,
box_markdown: HashMap::new(),
box_names: HashMap::new(),
box_duplicates: HashSet::new(),
box_open: None,
box_spans: Vec::new(),
bold: 0,
italic: 0,
strike: 0,
underline: 0,
superscript: 0,
subscript: 0,
mark: 0,
mark_color: Vec::new(),
dropped_html: Vec::new(),
code: 0,
link: 0,
html_links: 0,
pieces: Pieces::default(),
change: None,
serial: 0,
guessed_wraps: Vec::new(),
slot: 0,
span_start: None,
closed: None,
substituted: None,
substitution: None,
comment_anchor: None,
attribution_open: false,
paragraph_attribution: false,
pending_scopes: Vec::new(),
range_end_at: None,
shared_range: None,
unplaced: HashMap::new(),
held_in: Vec::new(),
id_line: None,
paragraph_in_comments: None,
page_break_due: false,
page_break_change: None,
run_after_close: false,
scope: None,
groups: 0,
anchor: None,
comment: None,
field_code: None,
authors: HashMap::new(),
ranged: BTreeMap::new(),
ranged_comments: BTreeMap::new(),
range_ended: HashSet::new(),
document: Document::default(),
}
}
fn story(&mut self) -> &mut Vec<Item> {
match &self.target {
Some(label) => self.definitions.entry(label.clone()).or_default(),
None => &mut self.body,
}
}
fn event(&mut self, event: Event<'_>) {
match event {
Event::Start(tag) => self.start(tag),
Event::End(tag) => self.end(tag),
Event::Text(text) if self.html_block.is_some() => {
if let Some(block) = &mut self.html_block {
block.push_str(&text);
}
}
Event::Text(text) if self.drawing_block.is_some() => {
if let Some((_, _, block)) = &mut self.drawing_block {
block.push_str(&text);
}
}
Event::Text(text) => self.text(&text),
Event::Code(text) => {
self.soft_break_resolved(true);
self.code += 1;
self.text(&text);
self.code -= 1;
}
Event::InlineMath(text) => self.math(&text, false),
Event::DisplayMath(text) => self.math(&text, true),
Event::InlineHtml(html) => self.inline_html(&html),
Event::Html(html) => match &mut self.html_block {
Some(block) => block.push_str(&html),
None => self.id_lines(&html),
},
Event::FootnoteReference(label) => self.note_reference(&label),
Event::SoftBreak => self.soft_break = true,
Event::HardBreak => {
if let Some(comment) = &mut self.comment {
comment.paragraphs.push(String::new());
} else {
self.push(Content::Break);
}
}
Event::Rule => {
self.end_paragraph();
self.begin_paragraph();
if let Some(index) = self.paragraph
&& let Some(Item::Paragraph(paragraph)) = self.story().get_mut(index)
{
paragraph.rule = true;
}
self.end_paragraph();
}
Event::TaskListMarker(checked) => {
self.push(Content::Text(
if checked { "\u{2612} " } else { "\u{2610} " }.to_string(),
));
self.paragraph_runs -= 1;
let index = self.story().len() - 1;
self.prefix_runs.push(index);
}
}
}
fn start(&mut self, tag: Tag<'_>) {
match tag {
Tag::Paragraph => {
self.end_paragraph();
self.begin_paragraph();
}
Tag::Heading { level, .. } => {
self.end_paragraph();
self.heading = Some(heading_level(level));
self.begin_paragraph();
}
Tag::BlockQuote(_) => {
self.end_paragraph();
self.quote += 1;
}
Tag::CodeBlock(kind) => {
self.end_paragraph();
self.code_block = true;
self.begin_paragraph();
if let CodeBlockKind::Fenced(info) = &kind {
let mut words = info.split_whitespace();
if let Some(lang) = words.next()
&& matches!(lang, "svg" | "mermaid")
&& let Some(name) = words.next()
{
self.drawing_block =
Some((lang.to_string(), name.to_string(), String::new()));
}
}
}
Tag::List(first) => {
self.end_paragraph();
let level = self
.item_levels
.get(self.item_count)
.copied()
.flatten()
.unwrap_or_else(|| u32::try_from(self.lists.len()).unwrap_or(8).min(8));
let instance = match first {
Some(start) => {
self.document.lists.push(List {
ordered: true,
level,
start: u32::try_from(start).unwrap_or(u32::MAX),
});
self.document.lists.len() - 1
}
None => *self.bullets.get_or_insert_with(|| {
self.document.lists.push(List {
ordered: false,
level: 0,
start: 1,
});
self.document.lists.len() - 1
}),
};
self.lists.push(OpenList {
instance,
level,
paragraphs: 0,
});
}
Tag::Item => {
self.end_paragraph();
let level = self.item_levels.get(self.item_count).copied().flatten();
self.item_count += 1;
if let Some(list) = self.lists.last_mut() {
list.paragraphs = 0;
list.level = level.unwrap_or(list.level);
}
}
Tag::FootnoteDefinition(label) => {
self.textless_paragraph();
self.end_paragraph();
let (counted, breaks) = self
.note_breaks
.get(self.note_count)
.copied()
.unwrap_or_default();
self.note_paragraph_breaks = counted > 1 && breaks + 1 == counted;
self.note_style = std::mem::take(&mut self.note_style_next);
self.note_spacing = std::mem::take(&mut self.note_spacing_next);
self.note_paragraph = 0;
self.note_count += 1;
let label = note_label(&label);
if counted > 1 && !self.note_paragraph_breaks {
let styles = match self.note_style.split_first() {
Some((first, rest)) if !rest.is_empty() => {
format!(", in style {first}; {} are not written", rest.join(", "))
}
_ => String::new(),
};
self.document.warnings.push(format!(
"[^{label}]: its id line counts {counted} paragraphs and its text \
{} by its <br>s: the <br>s are written as line breaks{styles}",
breaks + 1
));
}
let nth = {
let defined = self.label_defined.entry(label.clone()).or_insert(0);
*defined += 1;
*defined - 1
};
let label = nth_label(&label, nth);
if std::mem::take(&mut self.endnote_next) {
self.endnotes.insert(label.clone());
}
self.target = Some(label);
}
Tag::Table(alignments) => {
self.end_paragraph();
let mut columns: Vec<_> = alignments.iter().map(|a| alignment(*a)).collect();
self.table_plan = self
.tables
.get(self.table_count)
.cloned()
.flatten()
.filter(|_| self.view);
let mut grid = columns.clone();
if let Some(count) = self.table_plan.as_ref().and_then(|plan| plan.columns) {
grid.resize(count, None);
columns.resize(count.max(columns.len()), None);
}
let align = self.table_plan.as_ref().and_then(|plan| plan.align);
let style = self
.table_plan
.as_ref()
.and_then(|plan| plan.style.clone())
.or_else(|| {
self.document
.table_style
.as_ref()
.map(|(id, _, _)| id.clone())
})
.or_else(|| Some("TableGrid".to_string()))
.filter(|id| id != "TableNormal");
if let Some(id) = &style {
let legend = self
.document
.table_style
.as_ref()
.filter(|(legend, ..)| legend == id)
.map(|(_, border, name)| (border.clone(), name.clone()))
.or_else(|| self.document.table_legend.get(id).cloned());
let border = legend.as_ref().and_then(|(border, _)| border.clone());
let name = legend.and_then(|(_, name)| name);
if id == "TableGrid"
&& matches!(border, None | Some(view_styles::TableBorders::All(4)))
&& name.is_none()
{
self.document.styles.insert("TableGrid");
} else {
self.document
.table_styles
.insert(id.clone(), (border, name));
}
}
let formats = self.table_formats();
let mut geometry = self
.table_plan
.as_ref()
.map(|plan| plan.geometry.clone())
.unwrap_or_default();
if let Some(widths) = &geometry.widths
&& widths.len() != grid.len().max(1)
{
self.document.warnings.push(format!(
"t{}: its widths name {} columns and its grid has {}: the columns \
split the text width evenly",
self.table_count,
widths.len(),
grid.len().max(1)
));
geometry.widths = None;
}
self.story().push(Item::Table {
columns: grid,
align,
style,
formats,
geometry,
});
self.table = Some(columns);
self.table_count += 1;
self.row_number = 0;
}
Tag::TableHead => self.begin_row(true),
Tag::TableRow => self.begin_row(false),
Tag::TableCell => {
let grid = if self.row_shapes.is_empty() {
self.column
} else {
self.row_before
+ self
.row_shapes
.iter()
.take(self.column)
.map(|shape| match shape {
CellShape::Cell { across, .. } => *across,
CellShape::Spanned => 0,
})
.sum::<usize>()
};
let align = self
.table
.as_ref()
.and_then(|columns| columns.get(grid).copied())
.flatten();
let shape = self.row_shapes.get(self.column).copied();
self.column += 1;
let (across, merge) = match shape {
Some(CellShape::Spanned) => {
self.spanned = true;
return;
}
Some(CellShape::Cell { across, merge }) => (across, merge),
None => (1, None),
};
self.cell = Some(align);
self.story().push(Item::Cell {
align,
across,
merge,
});
}
Tag::Emphasis => self.italic += 1,
Tag::Strong => self.bold += 1,
Tag::Strikethrough => self.strike += 1,
Tag::Superscript => self.superscript += 1,
Tag::Subscript => self.subscript += 1,
Tag::Link {
link_type,
dest_url,
title,
..
} => {
let title = (!title.is_empty()).then(|| critic::decode(&title));
let dest = critic::decode(&dest_url);
let dest = if link_type == LinkType::Email && !dest.starts_with("mailto:") {
format!("mailto:{dest}")
} else {
dest
};
self.link_start(&dest, title);
}
Tag::Image { dest_url, id, .. } => {
if self.image.is_none() {
self.image = Some((
critic::decode(&dest_url),
critic::decode(&id),
String::new(),
Vec::new(),
));
}
}
Tag::MetadataBlock(_) => self.metadata = Some(String::new()),
Tag::HtmlBlock => self.html_block = Some(String::new()),
Tag::DefinitionList | Tag::DefinitionListTitle | Tag::DefinitionListDefinition => {}
}
}
fn end(&mut self, tag: TagEnd) {
if matches!(
tag,
TagEnd::Paragraph | TagEnd::Heading(_) | TagEnd::Item | TagEnd::TableCell
) {
self.close_inline_tags();
}
match tag {
TagEnd::Paragraph => self.end_paragraph(),
TagEnd::Heading(_) => {
self.end_paragraph();
self.heading = None;
}
TagEnd::BlockQuote(_) => {
self.end_paragraph();
self.quote = self.quote.saturating_sub(1);
}
TagEnd::CodeBlock => {
if let Some((lang, name, text)) = self.drawing_block.take() {
use super::from_docx::drawing;
let dest = self.document.drawing_backings.get(&name).cloned();
let drawing = dest.and_then(|dest| drawing::decode(&dest).ok()).and_then(
|mut drawing| match lang.as_str() {
"svg" => {
use base64::Engine;
drawing
.fill_slot_data(
&base64::engine::general_purpose::STANDARD
.encode(text.trim().as_bytes()),
"image/svg+xml",
)
.then_some(drawing)
}
_ if drawing.mermaid_unchanged(&text) => Some(drawing),
_ if drawing.rebuild_mermaid(&text) => Some(drawing),
_ => {
self.document.warnings.push(format!(
"mermaid '{name}' names a drawing this text cannot edit"
));
Some(drawing)
}
},
);
match drawing {
Some(drawing) => {
if let Some(index) = self.paragraph
&& let Some(Item::Paragraph(paragraph)) =
self.story().get_mut(index)
{
paragraph.style = None;
}
self.document.drawings.push(drawing);
let index = self.document.drawings.len() - 1;
self.push(Content::Drawing(index));
}
None => self.plain(&text),
}
}
let story = self.story();
if matches!(
story.last(),
Some(Item::Run(Run {
content: Content::Break,
..
}))
) {
story.pop();
}
self.end_paragraph();
self.code_block = false;
}
TagEnd::List(_) => {
self.end_paragraph();
self.lists.pop();
}
TagEnd::Item => self.end_paragraph(),
TagEnd::FootnoteDefinition => {
self.end_paragraph();
self.target = None;
self.note_style.clear();
self.note_spacing.clear();
self.note_paragraph_breaks = false;
}
TagEnd::Table => {
self.story().push(Item::TableEnd);
if !self.table_in_range() {
self.pending_scopes.clear();
self.range_end_at = None;
self.shared_range = None;
}
self.table = None;
self.table_plan = None;
self.row_breaks = false;
self.cell_paragraph = None;
self.row_shapes.clear();
self.row_pad.clear();
}
TagEnd::TableHead | TagEnd::TableRow => {
let mut column = self.row_before
+ self
.row_shapes
.iter()
.map(|shape| match shape {
CellShape::Cell { across, .. } => *across,
CellShape::Spanned => 0,
})
.sum::<usize>();
for (across, merge) in std::mem::take(&mut self.row_pad) {
let align = self
.table
.as_ref()
.and_then(|columns| columns.get(column).copied())
.flatten();
column += across;
self.cell = Some(align);
self.story().push(Item::Cell {
align,
across,
merge,
});
self.begin_paragraph();
self.end_paragraph();
self.cell = None;
self.story().push(Item::CellEnd);
}
self.end_row();
}
TagEnd::TableCell if std::mem::take(&mut self.spanned) => {}
TagEnd::TableCell => {
if self.paragraph.is_none() {
self.begin_paragraph();
}
self.end_paragraph();
self.cell = None;
self.story().push(Item::CellEnd);
}
TagEnd::Emphasis => self.italic = self.italic.saturating_sub(1),
TagEnd::Strong => self.bold = self.bold.saturating_sub(1),
TagEnd::Strikethrough => self.strike = self.strike.saturating_sub(1),
TagEnd::Superscript => self.superscript = self.superscript.saturating_sub(1),
TagEnd::Subscript => self.subscript = self.subscript.saturating_sub(1),
TagEnd::Link => self.link_end(),
TagEnd::Image => self.picture(),
TagEnd::MetadataBlock(_) => {
if let Some(text) = self.metadata.take() {
self.metadata(&text);
}
}
TagEnd::HtmlBlock => {
if let Some(block) = self.html_block.take() {
if self.box_boundary(block.trim()) {
return;
}
if is_symbol_tag(block.trim()) {
self.end_paragraph();
self.begin_paragraph();
self.inline_html(block.trim());
self.end_paragraph();
return;
}
let view_lines = self.view
&& self.cell.is_none()
&& self.comment.is_none()
&& self.target.is_none();
if comments_only(&block) && (block.trim() == PAGE_BREAK_LINE || view_lines) {
self.id_lines(&block);
} else {
self.html_text(&block);
}
}
}
TagEnd::DefinitionList
| TagEnd::DefinitionListTitle
| TagEnd::DefinitionListDefinition => {}
}
}
fn after_changed_break(&mut self, index: usize, kind: Kind) -> bool {
self.story()[..index]
.iter()
.rev()
.find_map(|item| match item {
Item::Paragraph(p) => Some(p.mark == Some(kind) && !p.whole),
Item::Table { .. } | Item::TableEnd | Item::Cell { .. } | Item::CellEnd => {
Some(false)
}
_ => None,
})
.unwrap_or(false)
}
fn begin_row(&mut self, header: bool) {
self.column = 0;
let header = header
&& self
.table_plan
.as_ref()
.is_none_or(|plan| plan.header_repeats);
let row = self
.table_plan
.as_ref()
.and_then(|plan| plan.rows.get(self.row_number))
.cloned()
.unwrap_or_default();
self.row_breaks = row.breaks;
self.cell_paragraph = row.first;
self.row_shapes = row.cells;
self.row_pad = row.pad;
self.row_before = row.gaps.0;
self.row_number += 1;
let index = self.story().len();
self.story().push(Item::Row {
header,
change: None,
gaps: row.gaps,
});
self.row = Some((index, self.change));
self.row_cells = RowCells::Empty;
}
fn end_row(&mut self) {
self.story().push(Item::RowEnd);
let Some((index, open)) = self.row.take() else {
return;
};
let row_change = match (open, self.row_cells) {
(Some((kind, serial)), _) if self.change == Some((kind, serial)) => {
Some((kind, serial))
}
(_, RowCells::Whole(kind, serial)) if self.table_plan.is_none() => Some((kind, serial)),
_ => None,
};
let own = !self.resolved
&& self.table_plan.as_ref().is_some_and(|plan| {
plan.row_marks
.contains_key(&self.row_number.saturating_sub(1))
});
if let Some(row_change) = row_change.filter(|_| !own)
&& let Some(Item::Row { change, .. }) = self.story().get_mut(index)
{
*change = Some(row_change);
}
}
fn id_lines(&mut self, html: &str) {
if html.trim() == PAGE_BREAK_LINE
&& self.cell.is_none()
&& self.comment.is_none()
&& self.target.is_none()
{
self.break_page();
return;
}
if !self.view || self.cell.is_some() || self.comment.is_some() || self.target.is_some() {
return;
}
if !comments_only(html) {
return;
}
for line in html.lines() {
if line.trim_start().starts_with("<!-- page ") {
continue;
}
self.endnote_next = view_notes::endnote_line(line);
self.note_style_next = view_notes::note_styles(line).unwrap_or_default();
self.note_spacing_next = view_notes::note_spacings(line);
if self.endnote_next || view_notes::footnote_line(line) {
continue;
}
self.textless_paragraph();
if let Some(count) = view_notes::empty_paragraphs(line) {
self.end_paragraph();
if let Some(said) =
view_notes::id_line(line).filter(|said| *said != view_notes::IdLine::default())
{
for _ in 0..count {
self.id_line = Some(said.clone());
self.textless_paragraph();
}
continue;
}
for _ in 0..count {
let story = self.story();
story.push(Item::Paragraph(Paragraph::default()));
story.push(Item::ParagraphEnd);
}
} else {
self.id_line = view_notes::id_line(line);
}
}
}
fn html_text(&mut self, html: &str) {
let tokens = self.html_comment_tokens(html);
for token in tokens {
self.token(token);
}
if self.comment.is_some() {
return;
}
let (name, paragraphs) = html_block_text(html);
if let Some(name) = name
&& !self.dropped_html.contains(&name)
{
self.document.warnings.push(format!(
"HTML block <{name}> dropped: its text is kept, its markup is not"
));
self.dropped_html.push(name);
}
for text in paragraphs {
self.end_paragraph();
self.begin_paragraph();
self.text(&text);
self.end_paragraph();
}
}
fn textless_paragraph(&mut self) {
if self.id_line.is_some() {
self.end_paragraph();
self.begin_paragraph();
self.end_paragraph();
}
}
fn begin_paragraph(&mut self) {
let mut paragraph = Paragraph::default();
let list = self.lists.last_mut().map(|list| {
let first = list.paragraphs == 0;
list.paragraphs += 1;
(list.instance, list.level, first)
});
let list_indent = list.map(|(_, level, _)| 720 * (level + 1));
if let Some(level) = self.heading {
let legend = self.document.style_specs.iter().find(|spec| {
spec.heading == u32::try_from(level).ok() && spec.id != HEADINGS[level - 1]
});
paragraph.style = Some(match legend {
Some(spec) => Cow::Owned(spec.id.clone()),
None => HEADINGS[level - 1].into(),
});
paragraph.heading = true;
} else if self.code_block {
paragraph.style = Some("SourceCode".into());
paragraph.indent = list_indent;
} else if let Some((instance, level, first)) = list {
paragraph.style = Some("ListParagraph".into());
if first {
paragraph.numbering = Some((instance, level));
} else {
paragraph.indent = list_indent;
}
} else if self.quote > 0 {
paragraph.style = Some("Quote".into());
if self.quote > 1 {
paragraph.indent = Some(720 * self.quote);
}
} else if let Some(target) = &self.target {
let default = self
.document
.style_specs
.iter()
.find(|s| s.default)
.map_or("Normal", |s| s.id.as_str());
let spacing_at = self.note_paragraph;
let at = self
.note_paragraph
.min(self.note_style.len().saturating_sub(1));
self.note_paragraph += 1;
if let Some(spacing) = self.note_spacing.get(spacing_at) {
paragraph.spacing = *spacing;
}
paragraph.style = match self.note_style.get(at) {
Some(style) if style == default => None,
Some(style) => Some(style.clone().into()),
None if self.endnotes.contains(target) => Some("EndnoteText".into()),
None => Some("FootnoteText".into()),
};
}
if let Some(align) = self.cell {
paragraph.align = align;
}
self.paragraph_in_comments = None;
if self.cell.is_none()
&& self.target.is_none()
&& let Some(line) = self.id_line.take()
{
self.paragraph_in_comments = Some(line.in_comments.clone());
paragraph.number = Some(line.number);
let styled = line.style.is_some();
if let Some(style) = line.style {
paragraph.style = Some(style.into());
paragraph.outline = line
.outline
.and_then(|level| level.checked_sub(1))
.map(|level| level as usize)
.or_else(|| self.heading.map(|level| level - 1));
} else if let Some(outline) = line.outline {
paragraph.style = None;
paragraph.outline = outline.checked_sub(1).map(|level| level as usize);
}
paragraph.align = line.align.or(paragraph.align);
self.page_break_due = line.page_break;
self.page_break_change = line.page_break_change.clone().map(|(inserted, tag)| {
let kind = if inserted { Kind::Insert } else { Kind::Delete };
(kind, tag)
});
paragraph.section_break = line.section_break;
paragraph.ind = Indent {
first_line_chars: line.first_line_chars,
hanging_chars: line.hanging_chars,
left_chars: line.left_chars,
right_chars: line.right_chars,
first_line: line.first_line,
hanging: line.hanging,
left: line.left,
right: line.right,
};
paragraph.spacing = line.spacing;
paragraph.size = line.size;
paragraph.mark_inherits = line.mark_inherits;
if let Some(label) = line.label {
match (self.heading, &label) {
(Some(_), Label::Text(text)) => self.label_prefix = Some(format!("{text} ")),
(Some(_), Label::Bullet) => self.label_prefix = Some("- ".to_string()),
_ => {}
}
let level = line
.level
.unwrap_or_else(|| list.map_or(0, |(_, level, _)| level));
let start = list
.filter(|&(_, _, first)| first)
.and_then(|(instance, _, _)| self.document.lists.get(instance))
.filter(|list| list.ordered)
.map(|list| list.start);
paragraph.label = self.label_use(label, level, start);
if paragraph.label.is_some() {
paragraph.numbering = None;
paragraph.indent = None;
if !styled && list.is_some() {
paragraph.style = None;
}
}
}
paragraph.formats = line.fmt.iter().map(|tag| self.format_mark(tag)).collect();
if !self.resolved {
let mut unshown = Vec::new();
for (inserted, tag) in &line.rev {
let marks = self.unshown_marks(tag);
unshown.extend(marks.into_iter().map(|mark| (*inserted, mark)));
}
paragraph.unshown = unshown;
paragraph.holds = line
.holds
.iter()
.map(|event| (event.inserted, event.revision, event.comment, event.event))
.collect();
}
let mark = line
.break_ins
.map(|tag| (Kind::Insert, tag))
.or_else(|| line.break_del.map(|tag| (Kind::Delete, tag)));
self.fix_mark(&mut paragraph, mark);
}
if self.cell.is_some()
&& let Some(at) = self.cell_paragraph
{
self.cell_paragraph = Some(at + 1);
if let Some(align) = self
.table_plan
.as_ref()
.and_then(|plan| plan.aligns.get(&at).copied())
{
paragraph.align = Some(align);
}
if let Some(style) = self
.table_plan
.as_ref()
.and_then(|plan| plan.styles.get(&at).cloned())
{
paragraph.style = Some(style.into());
}
if let Some(spacing) = self
.table_plan
.as_ref()
.and_then(|plan| plan.spacings.get(&at).copied())
{
paragraph.spacing = spacing;
}
if let Some(size) = self
.table_plan
.as_ref()
.and_then(|plan| plan.sizes.get(&at).copied())
{
paragraph.size = Some(size);
paragraph.mark_inherits = self
.table_plan
.as_ref()
.is_some_and(|plan| plan.mark_inherits.contains(&at));
}
let formats = self
.table_plan
.as_ref()
.and_then(|plan| plan.para_fmt.get(&at).cloned())
.unwrap_or_default();
paragraph.formats = formats.iter().map(|tag| self.format_mark(tag)).collect();
if !self.resolved
&& let Some(tags) = self.unplaced.remove(&at)
{
for (kind, tag) in &tags {
if *kind == "fmt" {
let mark = self.format_mark(tag);
paragraph.formats.push(mark);
} else {
let marks = self.unshown_marks(tag);
paragraph
.unshown
.extend(marks.into_iter().map(|mark| (*kind == "ins", mark)));
}
}
}
let mark = self.table_plan.as_ref().and_then(|plan| {
let (inserted, tag) = view_notes::paragraph_mark(plan.marks.get(&at)?)?;
let kind = if inserted { Kind::Insert } else { Kind::Delete };
Some((kind, tag.clone()))
});
self.fix_mark(&mut paragraph, mark);
}
match ¶graph.style {
Some(Cow::Borrowed(style)) => {
self.document.styles.insert(style);
}
Some(Cow::Owned(style)) => {
self.document.named_styles.insert(style.clone());
}
None => {}
}
let index = self.story().len();
self.story().push(Item::Paragraph(paragraph));
self.paragraph = Some(index);
self.paragraph_serial += 1;
self.paragraph_runs = 0;
self.prefix_runs.clear();
}
fn table_formats(&mut self) -> TableFormats {
let Some(plan) = self.table_plan.as_ref() else {
return TableFormats::default();
};
let (table, rows, cells) = (
plan.fmt.clone(),
plan.row_fmt.clone(),
plan.cell_fmt.clone(),
);
let grid = plan.grid_fmt;
let (row_marks, cell_marks) = if self.resolved {
(BTreeMap::new(), BTreeMap::new())
} else {
(plan.row_marks.clone(), plan.cell_marks.clone())
};
if let Some(id) = grid {
self.document.reserved_ids.insert(id);
}
let (borders, cell_borders) = (plan.borders.clone(), plan.cell_borders.clone());
let row_borders = plan.row_borders.iter().cloned().collect();
TableFormats {
table: table.map(|tag| self.format_mark(&tag)),
grid,
borders,
cell_borders,
row_borders,
row_marks: row_marks
.into_iter()
.map(|(row, (inserted, tag))| {
let kind = if inserted { Kind::Insert } else { Kind::Delete };
(row, (kind, self.format_mark(&tag)))
})
.collect(),
cell_marks: cell_marks
.into_iter()
.map(|(cell, (kind, tag))| (cell, (kind, self.format_mark(&tag))))
.collect(),
rows: rows
.into_iter()
.map(|(row, tag)| (row, self.format_mark(&tag)))
.collect(),
cells: cells
.into_iter()
.map(|(cell, tag)| (cell, self.format_mark(&tag)))
.collect(),
}
}
fn format_mark(&mut self, tag: &view_notes::Tag) -> FormatMark {
let (author, mut date) = self.view_author(&tag.handle, tag.date.as_deref());
if tag.date.is_none()
&& let Some((_, last)) = self
.authors
.get(&tag.handle)
.and_then(|known| known.range.as_ref())
&& self.range_ended.insert(tag.handle.clone())
{
date = format!("{last}T23:59:59Z");
}
let id = tag.ids.first().copied();
if let Some(id) = id {
self.document.reserved_ids.insert(id);
}
FormatMark { id, author, date }
}
fn unshown_marks(&mut self, tag: &view_notes::Tag) -> Vec<FormatMark> {
let first = self.format_mark(tag);
let mut marks = vec![first.clone()];
for &id in tag.ids.iter().skip(1) {
self.document.reserved_ids.insert(id);
marks.push(FormatMark {
id: Some(id),
..first.clone()
});
}
marks
}
fn table_in_range(&self) -> bool {
self.table_plan.as_ref().is_some_and(|plan| plan.in_comment)
}
fn break_page(&mut self) {
self.end_paragraph();
let page_break = Item::Run(Run {
content: Content::PageBreak,
format: RunFormat::default(),
change: None,
scope: None,
});
let story = self.story();
if matches!(story.last(), Some(Item::ParagraphEnd)) {
let end = story.len() - 1;
story.insert(end, page_break);
} else {
story.push(Item::Paragraph(Paragraph::default()));
story.push(page_break);
story.push(Item::ParagraphEnd);
}
}
fn ensure_paragraph(&mut self) {
if self.paragraph.is_none() {
self.begin_paragraph();
}
}
fn end_paragraph(&mut self) {
self.soft_break_resolved(false);
let Some(index) = self.paragraph.take() else {
return;
};
self.label_prefix = None;
let page_break_change = self.page_break_change.take().map(|(kind, tag)| {
let before = self.story().iter().rev().find_map(|item| match item {
Item::Run(run) => Some(run.change),
_ => None,
});
match before.flatten() {
Some((k, serial))
if k == kind
&& !tag.ids.is_empty()
&& self.document.revision_ids.get(&serial) == Some(&tag.ids) =>
{
(k, serial)
}
_ => (kind, self.tag_serial(&tag)),
}
});
if std::mem::take(&mut self.page_break_due) {
self.story().push(Item::Run(Run {
content: Content::PageBreak,
format: RunFormat::default(),
change: page_break_change,
scope: None,
}));
}
if let Some(comment) = &mut self.comment {
comment.paragraphs.push(String::new());
}
let after_break = self
.span_start
.map(|span| span.kind)
.map(|kind| self.after_changed_break(index, kind));
if let (Some((_, serial)), Some(span)) = (self.change, self.span_start.as_mut())
&& span.serial == serial
&& span.paragraph == self.paragraph_serial
&& span.runs_before == self.paragraph_runs
&& self.cell.is_none()
{
span.at_break = Some(index);
}
let says_marks = self.view && (self.cell.is_some() || self.target.is_some());
let folded = |serial: u32| self.document.wraps.contains_key(&serial);
let (mark, whole) = match self.change {
Some((kind, serial)) => (Some((kind, serial)), false),
None => match self.span_start {
Some(span)
if !says_marks
&& span.at_start
&& span.paragraph == self.paragraph_serial
&& self.closed == Some(span.serial)
&& !self.document.revision_ids.contains_key(&span.serial)
&& !folded(span.serial)
&& !self.run_after_close
&& self.paragraph_runs > 0
&& !after_break.is_some_and(|after| after) =>
{
(Some((span.kind, span.serial)), true)
}
_ => (None, false),
},
};
let covered = self.span_start.and_then(|span| {
let starts = span.paragraph != self.paragraph_serial || span.at_start;
let ends = self.change == Some((span.kind, span.serial))
|| (self.closed == Some(span.serial)
&& !folded(span.serial)
&& !self.run_after_close);
(starts && ends).then_some((span.kind, span.serial))
});
let whole_in_cell = if whole { mark } else { covered };
if self.cell.is_some() && self.paragraph_runs > 0 {
let one_change = |before: u32, now: u32| {
self.document.revision_ids.get(&before) == self.document.revision_ids.get(&now)
};
self.row_cells = match (self.row_cells, whole_in_cell) {
(RowCells::Empty, Some((kind, serial))) => RowCells::Whole(kind, serial),
(RowCells::Whole(before, was), Some((kind, now)))
if before == kind && one_change(was, now) =>
{
RowCells::Whole(kind, now)
}
_ => RowCells::Mixed,
};
}
let shift = match (mark, self.span_start) {
(None, Some(span))
if span.paragraph != self.paragraph_serial
&& self.closed == Some(span.serial)
&& !folded(span.serial)
&& !self.run_after_close
&& self.paragraph_runs > 0
&& self.cell.is_none() =>
{
span.at_break
.filter(|&first| no_table_between(self.story(), first, index))
.map(|first| (first, span.kind, span.serial))
}
_ => None,
};
let story = self.story();
if let Some((first, kind, serial)) = shift
&& let Some(Item::Paragraph(paragraph)) = story.get_mut(first)
{
if !paragraph.mark_fixed {
paragraph.mark = None;
paragraph.mark_by = None;
}
if let Some(Item::Paragraph(paragraph)) = story.get_mut(index)
&& !paragraph.mark_fixed
{
paragraph.mark = Some(kind);
paragraph.mark_by = Some(serial);
paragraph.whole = false;
}
} else if let Some(Item::Paragraph(paragraph)) = story.get_mut(index)
&& !paragraph.mark_fixed
{
paragraph.mark = mark.map(|(kind, _)| kind);
paragraph.mark_by = mark.map(|(_, serial)| serial);
paragraph.whole = whole;
}
story.push(Item::ParagraphEnd);
}
fn format(&self) -> RunFormat {
RunFormat {
bold: self.bold > 0,
italic: self.italic > 0,
strike: self.strike > 0,
underline: self.underline > 0,
superscript: self.superscript > 0,
subscript: self.subscript > 0,
mark: self.mark > 0,
mark_color: self.mark_color.last().copied(),
code: self.code > 0,
link: self.link > 0,
}
}
fn push(&mut self, content: Content) {
self.ensure_paragraph();
let blank = matches!(&content, Content::Text(text) if text.trim().is_empty())
|| matches!(content, Content::Tab | Content::Break);
if self.scope.is_none() && self.change.is_none() && !blank {
self.pending_scopes.clear();
self.range_end_at = None;
self.shared_range = None;
}
if self.code > 0 {
self.document.styles.insert("VerbatimChar");
}
if let Content::Text(ref text) = content {
let last_prefix = self.prefix_runs.last().copied();
if last_prefix != Some(self.story().len() - 1) {
let now = self.format();
let current_change = self.change;
let current_scope = self.scope.map(|(_, group)| group);
let story = self.story();
let last = story.last_mut();
let merge = matches!(
last,
Some(Item::Run(Run {
content: Content::Text(_),
format,
change,
scope,
})) if *format == now && *change == current_change && *scope == current_scope
);
if merge
&& let Some(Item::Run(Run {
content: Content::Text(prev_text),
..
})) = last
{
prev_text.push_str(text);
return;
}
}
}
let run = Run {
content,
format: self.format(),
change: self.change,
scope: self.scope.map(|(_, group)| group),
};
self.story().push(Item::Run(run));
self.paragraph_runs += 1;
self.run_after_close = true;
self.anchor = None;
}
fn text(&mut self, text: &str) {
if self.metadata.is_some() || self.image.is_some() || !self.options.critic {
self.soft_break_resolved(true);
}
if let Some(metadata) = &mut self.metadata {
metadata.push_str(text);
return;
}
if let Some((_, _, alt, loose)) = &mut self.image {
let mut tokens = Vec::new();
self.pieces.feed(text, |piece| match piece {
Piece::Text(text) => alt.push_str(text),
Piece::Token(token) => tokens.push(token),
});
loose.extend(loose_tokens(tokens));
return;
}
if !self.options.critic {
self.plain(text);
return;
}
let mut pieces = Vec::new();
self.pieces.feed(text, |piece| {
pieces.push(match piece {
Piece::Text(text) => Ok(text.to_string()),
Piece::Token(token) => Err(token),
});
});
for piece in pieces {
match piece {
Ok(text) => {
self.soft_break_resolved(true);
self.plain(&text);
}
Err(token) => {
if self.soft_break {
self.held.push(token);
} else {
self.token(token);
}
}
}
}
}
fn soft_break_resolved(&mut self, words: bool) {
if std::mem::take(&mut self.soft_break) && words {
self.plain(" ");
}
for token in std::mem::take(&mut self.held) {
self.token(token);
}
}
fn math(&mut self, latex: &str, display: bool) {
self.soft_break_resolved(true);
if self.metadata.is_some() || self.image.is_some() || self.comment.is_some() {
let fence = if display { "$$" } else { "$" };
let critic = self.options.critic;
let latex = if critic {
critic::restore(latex)
} else {
latex.to_string()
};
let text = format!("{fence}{latex}{fence}");
if let Some(metadata) = &mut self.metadata {
metadata.push_str(&text);
} else if let Some((_, _, alt, _)) = &mut self.image
&& !critic
{
alt.push_str(&text);
} else if let Some((_, _, alt, loose)) = &mut self.image {
let mut tokens = Vec::new();
self.pieces.feed(&text, |piece| match piece {
Piece::Text(text) => alt.push_str(text),
Piece::Token(token) => tokens.push(token),
});
loose.extend(loose_tokens(tokens));
} else {
self.plain(&text);
}
return;
}
let mut source = String::with_capacity(latex.len());
if self.options.critic {
Pieces::default().feed(latex, |piece| match piece {
Piece::Text(text) => math::literal_markers(text, &mut source),
Piece::Token(Token::InsertStart) => source.push(math::INSERT_START),
Piece::Token(Token::InsertEnd) => source.push(math::INSERT_END),
Piece::Token(Token::DeleteStart) => source.push(math::DELETE_START),
Piece::Token(Token::DeleteEnd) => source.push(math::DELETE_END),
Piece::Token(token) => source.push_str(critic::delimiter(token)),
});
} else {
math::literal_markers(latex, &mut source);
}
self.push(Content::Math {
latex: source,
display,
});
}
fn plain(&mut self, text: &str) {
let mut text = text;
if self.comment.is_none()
&& let Some(prefix) = self.label_prefix.take()
{
if let Some(rest) = text.strip_prefix(prefix.as_str()) {
if rest.is_empty() {
return;
}
text = rest;
} else if let Some(left) = prefix.strip_prefix(text) {
self.label_prefix = Some(left.to_string());
return;
}
}
if text.is_empty() {
return;
}
if let Some(comment) = &mut self.comment {
if let Some(last) = comment.paragraphs.last_mut() {
critic::push_escaped(last, text);
}
return;
}
if let Some(code) = &mut self.field_code {
code.push_str(text);
return;
}
let lines: Vec<&str> = if self.code_block {
text.split('\n').collect()
} else {
vec![text]
};
for (index, line) in lines.iter().enumerate() {
if index > 0 {
self.push(Content::Break);
}
for (at, part) in line.split('\t').enumerate() {
if at > 0 {
self.push(Content::Tab);
}
if !part.is_empty() {
self.push(Content::Text(part.to_string()));
}
}
}
}
fn new_slot(&mut self) -> usize {
self.document.slots.push(None);
self.document.slots.len() - 1
}
fn open(&mut self, kind: Kind) {
self.ensure_paragraph();
self.serial += 1;
self.change = Some((kind, self.serial));
self.slot = self.new_slot();
let slot = self.slot;
self.story().push(Item::RangeStart(slot));
if self.paragraph_runs == 0 {
let change = self.change;
for index in std::mem::take(&mut self.prefix_runs) {
if let Some(Item::Run(run)) = self.story().get_mut(index) {
run.change = change;
}
}
}
self.span_start = Some(SpanStart {
serial: self.serial,
kind,
paragraph: self.paragraph_serial,
at_start: self.paragraph_runs == 0,
runs_before: self.paragraph_runs,
at_break: None,
});
self.anchor = None;
}
fn close(&mut self) {
let serial = self.change.take().map(|(_, serial)| serial);
self.anchor = Some(Anchor {
slot: self.slot,
group: None,
serials: [self.substituted.take(), serial],
attributed: 0,
});
self.closed = self.span_start.map(|span| span.serial);
self.run_after_close = false;
}
fn token(&mut self, token: Token) {
if self.comment.is_some() {
match token {
Token::CommentEnd | Token::AttributionEnd => self.end_comment(),
Token::CommentBreak => {
if let Some(comment) = &mut self.comment {
comment.paragraphs.push(String::new());
}
}
Token::InsertStart
| Token::InsertEnd
| Token::DeleteStart
| Token::DeleteEnd
| Token::SubstituteStart
| Token::SubstituteSeparator
| Token::SubstituteEnd => {
if let Some(comment) = &mut self.comment
&& let Some(last) = comment.paragraphs.last_mut()
{
last.push(critic::stand_in(token));
}
}
_ => {}
}
return;
}
match token {
Token::InsertStart => self.open(Kind::Insert),
Token::DeleteStart => self.open(Kind::Delete),
Token::SubstituteStart => {
self.open(Kind::Delete);
self.substitution = Some((self.story().len(), None));
}
Token::SubstituteSeparator => {
self.substituted = self.change.map(|(_, serial)| serial);
self.serial += 1;
self.change = Some((Kind::Insert, self.serial));
self.span_start = None;
let at = self.story().len();
if let Some((_, split)) = &mut self.substitution {
*split = Some(at);
}
}
Token::InsertEnd | Token::DeleteEnd => self.close(),
Token::SubstituteEnd => {
self.close();
}
Token::HighlightStart => {
self.ensure_paragraph();
let slot = self.new_slot();
self.story().push(Item::RangeStart(slot));
self.shared_range = None;
self.scope = Some((slot, self.groups));
self.groups += 1;
self.anchor = None;
}
Token::HighlightEnd => {
if let Some((slot, group)) = self.scope.take() {
self.pending_scopes.push((slot, group));
self.range_end_at = Some(self.story().len());
self.anchor = Some(Anchor {
slot,
group: Some(group),
serials: [None, None],
attributed: 0,
});
}
}
Token::AttributionStart | Token::ParagraphInsertion => {
self.attribution_open = true;
self.paragraph_attribution = token == Token::ParagraphInsertion;
self.begin_comment();
}
Token::AttributionEnd => {}
Token::CommentStart => self.begin_comment(),
Token::CommentEnd => {}
Token::CommentBreak => {}
Token::MarkStart => self.mark += 1,
Token::MarkEnd => self.mark = self.mark.saturating_sub(1),
Token::FieldStart => self.field_code = Some(String::new()),
Token::FieldSeparator => {
let code = self.field_code.take().unwrap_or_default();
self.push(Content::FieldBegin(code));
}
Token::FieldEnd => self.push(Content::FieldEnd),
}
}
fn begin_comment(&mut self) {
let id = u32::try_from(self.document.comments.len()).unwrap_or(u32::MAX);
if self.paragraph_attribution {
self.ensure_paragraph();
self.comment = Some(Comment {
id,
paragraphs: vec![String::new()],
..Comment::default()
});
return;
}
match self.anchor.take() {
Some(anchor) if self.attribution_open && anchor.takes_attribution() => {
self.comment_anchor = Some(anchor);
}
Some(anchor) => self.anchor_comment(anchor, id),
None => self.anchor_here(id),
}
if self.paragraph_attribution {
self.comment_anchor = None;
self.ensure_paragraph();
}
self.comment = Some(Comment {
id,
paragraphs: vec![String::new()],
..Comment::default()
});
}
fn anchor_comment(&mut self, anchor: Anchor, id: u32) {
let pieces = std::mem::take(&mut self.pending_scopes);
match anchor.group {
Some(group) => {
let slot = pieces.first().map_or(anchor.slot, |(slot, _)| *slot);
self.document.slots[slot] = Some(id);
self.shared_range = Some(slot);
self.document.commented.insert(group);
for (_, group) in pieces {
self.document.commented.insert(group);
}
}
None => self.document.slots[anchor.slot] = Some(id),
}
}
fn anchor_here(&mut self, id: u32) {
if self.pending_scopes.is_empty()
&& let Some(slot) = self.shared_range
{
self.document.shared.entry(slot).or_default().push(id);
return;
}
if let Some(&(slot, group)) = self.pending_scopes.last() {
let anchor = Anchor {
slot,
group: Some(group),
serials: [None, None],
attributed: 0,
};
self.anchor_comment(anchor, id);
return;
}
self.ensure_paragraph();
let slot = self.new_slot();
self.document.slots[slot] = Some(id);
self.story().push(Item::RangeStart(slot));
}
fn note_moves(&mut self, names: &[Option<String>], serials: &[u32]) {
if names.len() == 1 {
if let Some(name) = names.first().cloned().flatten() {
for serial in serials {
self.document.moves.insert(*serial, name.clone());
}
}
return;
}
for (name, serial) in names.iter().zip(serials) {
if let Some(name) = name {
self.document.moves.insert(*serial, name.clone());
}
}
}
fn end_comment(&mut self) {
let Some(mut comment) = self.comment.take() else {
return;
};
let joined = comment.paragraphs.join("\n");
let (note, move_names) = peeled_note(&joined);
if note != joined {
comment.paragraphs = vec![note];
}
let is_attribution = std::mem::take(&mut self.attribution_open);
if std::mem::take(&mut self.paragraph_attribution) {
let whole = comment.paragraphs.join("\n");
let tag = view_notes::revision_tags(&whole).and_then(|tags| tags.into_iter().next());
let serial = if let Some(tag) = tag {
self.tag_serial(&tag)
} else if let Some(plain) = view_notes::plain_revision(&whole) {
self.serial += 1;
self.document
.attributions
.insert(self.serial, (plain.author, plain.date));
self.pool(&plain.ids, &[self.serial]);
self.name_revision(self.serial, plain.ids);
self.serial
} else {
return;
};
self.note_moves(&move_names, &[serial]);
self.ensure_paragraph();
if let Some(index) = self.paragraph
&& let Item::Paragraph(p) = &mut self.story()[index]
{
p.mark_fixed = true;
p.mark = Some(Kind::Insert);
p.mark_by = Some(serial);
}
return;
}
if let Some(mut anchor) = self.comment_anchor.take().filter(|_| is_attribution) {
let whole = comment.paragraphs.join("\n");
let sole = self
.sole_change(&anchor)
.or_else(|| anchor.serials[0].map(|old| (Kind::Delete, old)));
if let Some((kind, inner)) = sole
&& let Some(tags) = view_notes::nested_revision_tags(&whole)
{
let (author, date) = self.view_author(&tags[0].handle, tags[0].date.as_deref());
self.document
.attributions
.insert(inner, (author.clone(), date.clone()));
let mut old_ids = tags[0].ids.clone();
let mut own = vec![inner];
if let Some(new) = anchor.serials[0].and(anchor.serials[1]) {
let (old, inserted) = view_stories::substitution_ids(&tags[0].ids);
old_ids = old.to_vec();
self.name_revision(new, inserted.to_vec());
self.document.attributions.insert(new, (author, date));
own.push(new);
}
self.pool(&tags[0].ids, &own);
if !old_ids.is_empty() {
self.name_revision(inner, old_ids);
}
if let Some(tag) = tags.get(1) {
let established = self.established_kind(&tag.ids);
if established.is_none() && !tag.ids.is_empty() {
self.guessed_wraps.push((inner, self.target.clone()));
}
let parent = established.unwrap_or_else(|| other(kind));
let outer = (parent, self.tag_serial(tag));
self.document.wraps.insert(inner, outer);
self.unshown_rebuilt(&[outer.1]);
}
let mut serials = vec![inner];
if let Some(outer) = self.document.wraps.get(&inner).map(|outer| outer.1) {
serials.push(outer);
}
self.note_moves(&move_names, &serials);
return;
}
if let Some((kind, inner)) = sole
&& let Some(parts) = view_notes::nested_plain_revisions(&whole)
{
let first = &parts[0];
self.document
.attributions
.insert(inner, (first.author.clone(), first.date.clone()));
let mut old_ids = first.ids.clone();
let mut own = vec![inner];
if let Some(new) = anchor.serials[0].and(anchor.serials[1]) {
let (old, inserted) = view_stories::substitution_ids(&first.ids);
old_ids = old.to_vec();
self.name_revision(new, inserted.to_vec());
self.document
.attributions
.insert(new, (first.author.clone(), first.date.clone()));
own.push(new);
}
self.pool(&first.ids, &own);
if !old_ids.is_empty() {
self.name_revision(inner, old_ids);
}
if let Some(part) = parts.get(1) {
self.serial += 1;
let established = self.established_kind(&part.ids);
if established.is_none() && !part.ids.is_empty() {
self.guessed_wraps.push((inner, self.target.clone()));
}
let parent = established.unwrap_or_else(|| other(kind));
let outer = (parent, self.serial);
self.document
.attributions
.insert(outer.1, (part.author.clone(), part.date.clone()));
if !part.ids.is_empty() {
self.name_revision(outer.1, part.ids.clone());
}
self.pool(&part.ids, &[outer.1]);
self.document.wraps.insert(inner, outer);
}
let mut serials = vec![inner];
if let Some(outer) = self.document.wraps.get(&inner).map(|outer| outer.1) {
serials.push(outer);
}
self.note_moves(&move_names, &serials);
return;
}
if let Some(tags) = view_notes::revision_tags(&whole) {
let serials: Vec<u32> = if anchor.attributed == 0 {
anchor.serials.iter().flatten().copied().collect()
} else {
anchor.serials[1..].iter().flatten().copied().collect()
};
let ids = mark_ids(&tags, serials.len());
if let ([_], [deleted, inserted]) = (tags.as_slice(), serials.as_slice()) {
self.shared_tags.push((*deleted, *inserted));
}
if let [tag] = tags.as_slice() {
self.pool(&tag.ids, &serials);
} else if tags.len() == serials.len() {
for (tag, serial) in tags.iter().zip(&serials) {
self.pool(&tag.ids, &[*serial]);
}
}
let mut ranged = Vec::new();
for (i, serial) in serials.iter().enumerate() {
let tag = if tags.len() == 1 {
&tags[0]
} else {
&tags[i.min(tags.len() - 1)]
};
let (author, date) = self.view_author(&tag.handle, tag.date.as_deref());
self.document.attributions.insert(*serial, (author, date));
if tag.date.is_none()
&& self
.authors
.get(&tag.handle)
.is_some_and(|known| known.date.is_none() && known.range.is_some())
{
ranged.push((tag.handle.clone(), *serial));
}
if let Some(ids) = ids.get(i).filter(|ids| !ids.is_empty()) {
self.name_revision(*serial, ids.clone());
}
}
if serials.len() == 2 {
ranged.reverse();
}
for (handle, serial) in ranged {
self.ranged.entry(handle).or_default().push(serial);
}
let numbers: usize = tags.iter().map(|tag| tag.ids.len()).sum();
anchor.attributed += 1;
if serials.len() == 2 && numbers <= 1 {
self.anchor = anchor.takes_attribution().then_some(anchor);
}
self.note_moves(&move_names, &serials);
return;
}
if let Some(mut parts) = view_notes::plain_revisions(&whole) {
for plain in &mut parts {
if plain.ids.is_empty() && plain.author.is_empty() {
plain.author = self.options.author.to_string();
}
}
let serials: Vec<u32> = if anchor.attributed == 0 {
anchor.serials.iter().flatten().copied().collect()
} else {
anchor.serials[1..].iter().flatten().copied().collect()
};
let tags: Vec<_> = parts
.iter()
.map(|plain| view_notes::Tag {
handle: String::new(),
date: None,
ids: plain.ids.clone(),
})
.collect();
let ids = mark_ids(&tags, serials.len());
if parts.len() == 1
&& let [deleted, inserted] = serials.as_slice()
{
self.shared_tags.push((*deleted, *inserted));
}
if let [plain] = parts.as_slice() {
self.pool(&plain.ids, &serials);
} else if parts.len() == serials.len() {
for (plain, serial) in parts.iter().zip(&serials) {
self.pool(&plain.ids, &[*serial]);
}
}
for (i, serial) in serials.iter().enumerate() {
let plain = &parts[i.min(parts.len() - 1)];
self.document
.attributions
.insert(*serial, (plain.author.clone(), plain.date.clone()));
if let Some(ids) = ids.get(i).filter(|ids| !ids.is_empty()) {
self.name_revision(*serial, ids.clone());
}
}
anchor.attributed += 1;
if serials.len() == 2 && tags.iter().map(|tag| tag.ids.len()).sum::<usize>() <= 1 {
self.anchor = anchor.takes_attribution().then_some(anchor);
}
self.note_moves(&move_names, &serials);
return;
}
if let Some((author, date)) = attribution(whole.trim()) {
let author = author.unwrap_or_else(|| self.options.author.clone());
let serials = if anchor.attributed == 0 {
&anchor.serials[..]
} else {
&anchor.serials[1..]
};
for serial in serials.iter().flatten() {
self.document
.attributions
.insert(*serial, (author.clone(), date.to_string()));
}
anchor.attributed += 1;
self.anchor = anchor.takes_attribution().then_some(anchor);
return;
}
if anchor.attributed == 0 {
self.anchor_comment(anchor, comment.id);
} else {
self.anchor_here(comment.id);
}
}
while comment.paragraphs.len() > 1
&& comment
.paragraphs
.last()
.is_some_and(|p| p.trim().is_empty())
{
comment.paragraphs.pop();
}
let head = comment
.paragraphs
.first()
.and_then(|first| view_notes::comment_head(first.trim()))
.map(|(head, text)| (head, text.to_string()));
if let Some((head, text)) = head {
comment.style = self.document.comment_styles.get(&head.number).cloned();
comment.spacing = head.spacing;
comment.number = Some(head.number).filter(|&n| n <= view_notes::MOST_ID);
comment.parent = head.reply_to.filter(|&n| n <= view_notes::MOST_ID);
comment.done = head.resolved;
if !head.held_in.is_empty() {
if self.target.is_none() {
self.held_in
.push((comment.id, head.number, head.held_in.clone()));
} else {
self.document.warnings.push(format!(
"c{} is in {}: a note's comment holds no change's mark; its mark stays after its text",
head.number,
held_tag(&head.held_in)
));
}
}
if let Some(handle) = &head.handle {
let (author, date) = self.view_author(handle, head.date.as_deref());
comment.by = Some((author, date));
if head.date.is_none()
&& self
.authors
.get(handle)
.is_some_and(|known| known.range.is_some())
{
self.ranged_comments
.entry(handle.clone())
.or_default()
.push(comment.id);
}
if !handle.chars().any(|c| c.is_ascii_digit()) {
comment.initials = Some(handle.clone());
}
}
comment.paragraphs[0] = text;
} else if let Some(first) = comment.paragraphs.first_mut()
&& let Some((Some(author), date, rest)) = named(first.trim())
&& let Some(text) = rest.strip_prefix(':').or((rest.is_empty()).then_some(""))
{
comment.by = Some((author, date.to_string()));
*first = text.trim_start().to_string();
}
self.ensure_paragraph();
let id = comment.id;
let mut end_at = self
.range_end_at
.take()
.filter(|&at| self.paragraph.is_none_or(|start| at >= start));
let runs_in = |ids: &Vec<u32>| comment.number.map_or(!ids.is_empty(), |n| ids.contains(&n));
if self
.paragraph_in_comments
.as_ref()
.is_some_and(|ids| !runs_in(ids))
&& let Some(start) = self.paragraph
{
let mine: Vec<usize> = (0..self.document.slots.len())
.filter(|slot| {
self.document.slots[*slot] == Some(id)
|| self
.document
.shared
.get(slot)
.is_some_and(|ids| ids.contains(&id))
})
.collect();
let earlier = self.story()[..start]
.iter()
.any(|item| matches!(item, Item::RangeStart(slot) if mine.contains(slot)));
if earlier {
end_at = Some(start);
}
}
if let Some(change) = self.change {
let end_inside = match end_at {
None => true,
Some(at) => self.story()[..at]
.iter()
.rev()
.any(|item| matches!(item, Item::Run(run) if run.change == Some(change))),
};
self.document.note_changes.insert(id, (change, end_inside));
}
let story = self.story();
match end_at {
Some(at) if at <= story.len() => {
story.insert(at, Item::RangeEnd(id));
if let Some(start) = self.paragraph.filter(|&start| at <= start) {
self.paragraph = Some(start + 1);
}
}
_ => story.push(Item::RangeEnd(id)),
}
self.story().push(Item::CommentReference(id));
self.document.styles.insert("CommentText");
self.document.styles.insert("CommentReference");
self.document.comments.push(comment);
}
fn note_reference(&mut self, label: &str) {
if let Some(comment) = &mut self.comment {
if let Some(last) = comment.paragraphs.last_mut() {
critic::push_escaped(last, &format!("[^{}]", critic::decode(label)));
}
return;
}
if let Some(target) = &self.target {
let outer = target.split('\u{0}').next().unwrap_or_default();
let text = format!("[^{}]", critic::decode(label));
self.document.warnings.push(format!(
"[^{outer}]: {text} in its text is written as text: a note holds no note"
));
self.push(Content::Text(text));
return;
}
let label = note_label(label);
let uses = {
let uses = self.label_uses.entry(label.clone()).or_insert(0);
*uses += 1;
*uses - 1
};
let definitions = self.label_definitions.get(&label).copied().unwrap_or(1);
let label = nth_label(&label, if uses < definitions { uses } else { 0 });
let at = match self
.references
.iter()
.position(|(known, _)| *known == label)
{
Some(at) => at,
None => {
self.references.push((label, self.change));
self.references.len() - 1
}
};
let position = u32::try_from(at + 1).unwrap_or(u32::MAX);
self.push(Content::NoteReference(position));
}
fn dropped_tokens(&mut self, text: &str) -> Vec<Token> {
let mut tokens = Vec::new();
self.pieces.feed(text, |piece| {
if let Piece::Token(token) = piece {
tokens.push(token);
}
});
loose_tokens(tokens)
}
fn html_comment_tokens(&mut self, html: &str) -> Vec<Token> {
let mut rest = html;
let mut inner = String::new();
while let Some(open) = rest.find("<!--") {
let comment = &rest[open + 4..];
match comment.find("-->") {
Some(end) => {
inner.push_str(&comment[..end]);
rest = &comment[end + 3..];
}
None => {
inner.push_str(comment);
break;
}
}
}
self.dropped_tokens(&inner)
}
fn inline_html(&mut self, html: &str) {
if self.box_boundary(html.trim()) {
return;
}
if self.note_clause(html) {
return;
}
let Some(HtmlTag {
name,
closing,
empty,
}) = html_tag(html)
else {
let tokens = self.dropped_tokens(html);
for token in tokens {
self.token(token);
}
return;
};
if name == "br" {
if !closing {
if html_is_page_break(html) {
self.push(Content::PageBreak);
} else {
self.line_break(empty);
}
}
return;
}
if name == "sym" {
if empty && !closing {
let font = html_attribute(html, "font").unwrap_or_default();
let value = html_attribute(html, "char").unwrap_or_default();
if !font.is_empty() && !value.is_empty() {
self.push(Content::Symbol { font, value });
}
}
return;
}
if empty || self.comment.is_some() {
return;
}
if name == "a" {
if closing {
if self.html_links > 0 {
self.html_links -= 1;
self.link_end();
}
} else if let Some(href) = html_attribute(html, "href") {
let before = self.link;
let title = html_attribute(html, "title");
self.link_start(&href, title);
self.html_links += u32::from(self.link > before);
} else if let Some(name) =
html_attribute(html, "id").or_else(|| html_attribute(html, "name"))
&& !name.is_empty()
&& self.comment.is_none()
&& self.image.is_none()
{
self.ensure_paragraph();
self.story().push(Item::Bookmark(name));
}
return;
}
let counter = match name.as_str() {
"b" | "strong" => &mut self.bold,
"i" | "em" => &mut self.italic,
"s" | "del" | "strike" => &mut self.strike,
"u" | "ins" => &mut self.underline,
"sup" => &mut self.superscript,
"sub" => &mut self.subscript,
"code" => &mut self.code,
"mark" => &mut self.mark,
_ => {
if !self.dropped_html.contains(&name) {
self.document.warnings.push(format!(
"inline HTML <{name}> dropped: its text is kept, its markup is not"
));
self.dropped_html.push(name);
}
return;
}
};
if closing {
*counter = counter.saturating_sub(1);
} else {
*counter += 1;
}
if name == "mark" {
if closing {
self.mark_color.pop();
} else if let Some(colour) = html_attribute(html, "class")
.as_deref()
.and_then(|c| c.split_whitespace().find_map(hl_color_class))
{
self.mark_color.push(colour);
} else {
self.mark_color.push("yellow");
}
}
}
fn note_clause(&mut self, html: &str) -> bool {
let Some(label) = self.target.clone().filter(|_| self.view) else {
return false;
};
let Some(line) = html
.trim()
.strip_prefix("<!--")
.and_then(|rest| rest.strip_suffix("-->"))
.and_then(|inner| view_notes::id_line(&format!("<!-- p0 {} -->", inner.trim())))
.filter(|line| line.style.is_none() && !(line.rev.is_empty() && line.fmt.is_empty()))
else {
return false;
};
let story = self.story();
if let Some(Item::Run(Run {
content: Content::Text(text),
..
})) = story.last_mut()
{
text.truncate(text.trim_end().len());
if text.is_empty() {
story.pop();
}
}
self.note_clauses.insert(label, line);
true
}
fn link_start(&mut self, url: &str, title: Option<String>) {
if self.comment.is_some() || self.image.is_some() {
return;
}
self.ensure_paragraph();
let link = match url.strip_prefix('#') {
Some(anchor) => Link::Anchor(anchor.to_string()),
None => Link::External(url.to_string()),
};
self.story().push(Item::LinkStart(link, title));
self.document.styles.insert("Hyperlink");
self.link += 1;
}
fn link_end(&mut self) {
if self.link > 0 && self.comment.is_none() && self.image.is_none() {
self.link -= 1;
self.story().push(Item::LinkEnd);
}
}
fn close_inline_tags(&mut self) {
while self.html_links > 0 {
self.html_links -= 1;
self.link_end();
}
for counter in [
&mut self.bold,
&mut self.italic,
&mut self.strike,
&mut self.underline,
&mut self.superscript,
&mut self.subscript,
&mut self.code,
&mut self.mark,
] {
*counter = 0;
}
self.mark_color.clear();
}
fn line_break(&mut self, empty: bool) {
if let Some(comment) = &mut self.comment {
comment.paragraphs.push(String::new());
} else if !empty
&& ((self.cell.is_some() && self.row_breaks)
|| (self.target.is_some() && self.note_paragraph_breaks))
{
self.ensure_paragraph();
self.end_paragraph();
self.begin_paragraph();
} else {
self.push(Content::Break);
}
}
fn picture(&mut self) {
let Some((url, id, alt, loose)) = self.image.take() else {
return;
};
if url.starts_with("drawing:") {
match super::from_docx::drawing::decode(&url) {
Ok(drawing) => {
self.document.drawings.push(drawing);
let index = self.document.drawings.len() - 1;
if self.box_names.insert(id.clone(), index).is_some() {
self.box_duplicates.insert(id);
}
self.push(Content::Drawing(index));
}
Err(_) => self.plain(alt.trim()),
}
return;
}
if let Some((_mime, b64)) = super::from_docx::drawing::data_uri(&url) {
use super::from_docx::drawing;
if let Some(drawing) = drawing::lookup(
&id,
&self.document.drawing_defs,
&self.document.drawing_backings,
) {
self.document.drawings.push(drawing);
let index = self.document.drawings.len() - 1;
self.push(Content::Drawing(index));
return;
}
let picture =
drawing::base64_decode(b64).and_then(|bytes| read_picture(bytes, alt.trim()));
match picture {
Some(picture) => {
let index = self
.document
.pictures
.iter()
.position(|seen| seen.bytes == picture.bytes)
.unwrap_or_else(|| {
self.document.pictures.push(picture);
self.document.pictures.len() - 1
});
self.push(Content::Picture(index));
}
None => {
self.document
.warnings
.push(format!("image '{id}' was written as its alt text"));
self.plain(alt.trim());
}
}
return;
}
let loaded = self.options.images.map(|load| load(&url));
let picture = loaded
.flatten()
.and_then(|bytes| read_picture(bytes, alt.trim()));
match picture {
Some(picture) => {
self.document.pictures.push(picture);
let index = self.document.pictures.len() - 1;
self.push(Content::Picture(index));
}
None => {
if self.options.images.is_some() {
self.document
.warnings
.push(format!("image '{url}' was written as its alt text"));
}
self.plain(alt.trim());
}
}
for token in loose {
self.token(token);
}
}
fn comments_out_of_notes(&mut self) {
let mut moved: Vec<(u32, u32)> = Vec::new();
for (index, note) in self.document.notes.iter_mut().enumerate() {
let position = u32::try_from(index + 1).unwrap_or(u32::MAX);
for item in ¬e.items {
if let Item::RangeStart(slot) = item
&& let Some(id) = self.document.slots.get_mut(*slot).and_then(Option::take)
&& !moved.iter().any(|(_, seen)| *seen == id)
{
moved.push((position, id));
}
}
for item in ¬e.items {
if let Item::RangeEnd(id) | Item::CommentReference(id) = item {
self.document.note_changes.remove(id);
}
}
note.items
.retain(|item| !matches!(item, Item::RangeEnd(_) | Item::CommentReference(_)));
}
for (position, id) in moved {
let Some(at) = self.document.body.iter().position(|item| {
matches!(item, Item::Run(Run { content: Content::NoteReference(p), .. }) if *p == position)
}) else {
continue;
};
let slot = self.new_slot();
self.document.slots[slot] = Some(id);
self.document.body.splice(
at..=at,
[
Item::RangeStart(slot),
self.document.body[at].clone(),
Item::RangeEnd(id),
Item::CommentReference(id),
],
);
self.document.warnings.push(format!(
"comment in footnote {position} moved to its reference mark: Word shows comments only in the body"
));
}
}
fn stories(&mut self, number: usize, stories: view_stories::Stories) {
for name in &stories.dropped {
self.document.warnings.push(format!(
"section {number}: front matter {name} does not read and is dropped; quote its text ('…' keeps backslashes)"
));
}
self.document.stories.insert(number, stories);
}
fn metadata(&mut self, text: &str) {
self.authors = view_notes::authors(text);
for handle in view_notes::reversed_ranges(text) {
self.document.warnings.push(format!(
"authors: {handle}: its days run backwards (last..first), so its marks are written undated"
));
}
self.document.owner = view_notes::document_owner(text);
if view_notes::empty_owner(text) {
self.document.warnings.push(
"authors: document_owner: names no one, so the document's own owner stays; \
write `none` to clear it"
.to_string(),
);
}
self.document.table_style = view_styles::table_style(text);
self.document.table_legend = view_styles::table_legend(text);
for (id, name) in self
.document
.table_style
.iter()
.filter_map(|(id, _, name)| name.as_ref().map(|name| (id, name)))
.chain(
self.document
.table_legend
.iter()
.filter_map(|(id, (_, name))| name.as_ref().map(|name| (id, name))),
)
.filter(|(_, name)| name.contains(','))
{
self.document.warnings.push(format!(
"table: {id}, named {name}: a style's w:name holds no comma, \
so it is written '{}'",
name.replace(',', " ")
));
}
if let Some((id, None, _)) = &self.document.table_style
&& !super::package::is_built_in_table_style(id)
&& text.lines().any(|line| {
let line = view_styles::without_comment(line).trim();
line.starts_with("table: ") && line.contains(", borders vary")
})
{
self.document.warnings.push(format!(
"table: {id}, borders vary: the view does not say the borders, \
so the table style is written without them"
));
}
self.stories(1, view_stories::first_section(text));
self.document.style_specs = view_styles::legend(text);
let mut key_above = "";
for line in text.lines() {
let line = view_styles::without_comment(line);
if !line.starts_with(' ') {
key_above = line.split(':').next().unwrap_or("").trim();
} else if key_above == "sections"
&& let Some((number, page)) = view_notes::section_page(line)
{
if let Some(page) = page {
self.document.pages.insert(number, page);
}
match view_notes::section_earlier_page(line) {
Some(earlier) => self.document.earlier_pages.insert(number, earlier),
None => self.document.earlier_pages.remove(&number),
};
if let Some((_, entry)) = line.trim().split_once(": ") {
self.stories(number, view_stories::section(entry));
if let Some(tag) = view_notes::section_format(entry) {
let mark = self.format_mark(&tag);
self.document.section_formats.insert(number, mark);
}
}
}
if line.starts_with([' ', '\t']) {
continue;
}
let Some((key, value)) = line.split_once(':') else {
continue;
};
let text = value.trim();
let value = text.trim_matches(|c| c == '"' || c == '\'').trim();
if value.is_empty() {
if key.trim() == "track_changes" {
self.document
.warnings
.push("track_changes: with no value ignored: it is on or off".into());
}
continue;
}
match key.trim() {
"title" | "author" => {
let value = Some(critic::decode(&view_notes::scalar_and_comment(text).0));
if key.trim() == "title" {
self.document.title = value;
} else {
self.document.author = value;
}
}
"track_changes" => match value {
"on" => self.document.tracking = Some(true),
"off" => self.document.tracking = Some(false),
_ => self
.document
.warnings
.push(format!("track_changes: {value} ignored: it is on or off")),
},
"notes" => {
match view_notes::empty_notes(text) {
Ok(kinds) => self.document.empty_notes = kinds,
Err(why) => self.document.warnings.push(format!(
"notes: {why}, so the notes parts it names are not made"
)),
}
if let Some(tags) = view_notes::note_revisions(text) {
self.document.warnings.push(format!(
"notes: rev: {tags}: insertions and deletions in the \
separators are not written"
));
}
let formats = view_notes::note_formats(text);
for kind in ["footnote", "endnote"] {
let count = formats.iter().filter(|(k, _)| *k == kind).count();
if count > 2 {
self.document.warnings.push(format!(
"notes: fmt: {count} changes for the {kind}s' two separators; \
the rest are not written"
));
}
}
self.document.note_formats = formats;
}
"comments" => {
let value = view_notes::scalar_and_comment(text).0;
let (all, each) = view_notes::comment_styles(&value);
self.document.comment_style = all;
self.document.comment_styles = each;
}
"unplaced" => {
for (at, kind, tag) in view_notes::unplaced(text) {
self.unplaced.entry(at).or_default().push((kind, tag));
}
}
"style_changes" => {
if !self.resolved
&& let Some(map) = value
.strip_prefix('{')
.and_then(|map| map.strip_suffix('}'))
{
let mut grouped: Vec<(String, Vec<(StyleChangeKind, FormatMark)>)> =
Vec::new();
let mut legacy: Vec<(String, Vec<String>)> = Vec::new();
for entry in map.split(", ") {
let Some((holder, tags)) = entry.split_once(": ") else {
continue;
};
let holder = holder.trim_matches(|c| c == '"' || c == '\'');
let tags = tags.trim_matches(|c| c == '"' || c == '\'');
let mut marks = Vec::new();
let mut assumed = Vec::new();
for raw in tags.split("; ") {
let (kind, rest, bare) = style_change_tag(raw);
let Some(parsed) = view_notes::revision_tags(rest) else {
continue;
};
if bare {
assumed.push(rest.to_string());
}
for tag in parsed {
marks.push((kind, self.format_mark(&tag)));
}
}
if marks.is_empty() {
continue;
}
if !assumed.is_empty() {
if let Some((_, known)) =
legacy.iter_mut().find(|(name, _)| name == holder)
{
known.extend(assumed);
} else {
legacy.push((holder.to_string(), assumed));
}
}
if let Some((_, known)) =
grouped.iter_mut().find(|(name, _)| name == holder)
{
known.extend(marks);
} else {
grouped.push((holder.to_string(), marks));
}
}
self.document
.warnings
.extend(view_styles::style_change_warnings(&grouped, &legacy));
self.document.style_changes.extend(grouped);
}
}
"view" => {
self.view = true;
self.resolved =
value.starts_with("accept-all") || value.starts_with("reject-all");
}
"page" => {
if let Some(page) = view_notes::page_setup(value) {
self.document.pages.insert(1, page);
}
match view_notes::earlier_page(value) {
Some(earlier) => self.document.earlier_pages.insert(1, earlier),
None => self.document.earlier_pages.remove(&1),
};
if let Some(tag) = view_notes::section_format(value) {
let mark = self.format_mark(&tag);
self.document.section_formats.insert(1, mark);
}
}
_ => {}
}
}
let handles: Vec<String> = self.authors.keys().cloned().collect();
for handle in handles {
let person = self.view_author(&handle, None);
self.document.people.insert(handle, person);
}
let mut dropped: Vec<String> = self
.document
.stories
.values()
.flat_map(|stories| &stories.stories)
.filter(|story| {
std::iter::once(&story.text)
.chain(&story.more)
.any(|text| has_comment(text))
})
.map(|story| story.part.clone())
.collect();
dropped.sort_unstable();
dropped.dedup();
for part in dropped {
self.document.warnings.push(format!(
"comment in {part} dropped: Word shows comments only in the body, never in a header or footer"
));
}
}
fn established_kind(&self, ids: &[u32]) -> Option<Kind> {
if ids.is_empty() {
return None;
}
let story: &[Item] = match &self.target {
Some(label) => self.definitions.get(label).map(Vec::as_slice)?,
None => &self.body,
};
story.iter().rev().find_map(|item| match item {
Item::Run(Run {
change: Some((kind, serial)),
..
}) if self
.document
.revision_ids
.get(serial)
.is_some_and(|named| named.as_slice() == ids) =>
{
Some(*kind)
}
_ => None,
})
}
fn settle_guessed_wraps(&mut self) {
for (inner, target) in std::mem::take(&mut self.guessed_wraps) {
let Some(&(_, outer)) = self.document.wraps.get(&inner) else {
continue;
};
let Some(ids) = self.document.revision_ids.get(&outer).cloned() else {
continue;
};
let story: &[Item] = match &target {
Some(label) => self.definitions.get(label).map_or(&[][..], Vec::as_slice),
None => &self.body,
};
let first = story.iter().find_map(|item| match item {
Item::Run(Run {
change: Some((kind, serial)),
..
}) if *serial != inner
&& self
.document
.revision_ids
.get(serial)
.is_some_and(|named| *named == ids) =>
{
Some(*kind)
}
_ => None,
});
if let (Some(kind), Some(wrap)) = (first, self.document.wraps.get_mut(&inner)) {
wrap.0 = kind;
}
}
}
fn name_revision(&mut self, serial: u32, ids: Vec<u32>) {
self.document.revision_ids.insert(serial, ids);
self.document
.revision_lines
.insert(serial, self.source_line);
}
fn tag_serial(&mut self, tag: &view_notes::Tag) -> u32 {
self.serial += 1;
let serial = self.serial;
if tag.date.is_none()
&& self
.authors
.get(&tag.handle)
.is_some_and(|known| known.range.is_some())
{
self.ranged
.entry(tag.handle.clone())
.or_default()
.push(serial);
}
let attribution = self.view_author(&tag.handle, tag.date.as_deref());
self.document.attributions.insert(serial, attribution);
if !tag.ids.is_empty() {
self.name_revision(serial, tag.ids.clone());
}
self.pool(&tag.ids, &[serial]);
serial
}
fn note_serials(&mut self, label: &str, tags: &[view_notes::Tag]) -> Vec<u32> {
let target = self.target.replace(label.to_string());
let serials = tags.iter().map(|tag| self.tag_serial(tag)).collect();
self.target = target;
serials
}
fn pool(&mut self, ids: &[u32], serials: &[u32]) {
if ids.len() < 2 || serials.is_empty() {
return;
}
let story = match &self.target {
None => PoolStory::Body,
Some(label) if self.endnotes.contains(label) => PoolStory::Endnotes,
Some(_) => PoolStory::Footnotes,
};
let (notes, named) = self.pools.entry((story, ids.to_vec())).or_default();
*notes += 1;
named.extend_from_slice(serials);
}
fn sole_change(&self, anchor: &Anchor) -> Option<(Kind, u32)> {
let serials: Vec<u32> = anchor.serials.iter().flatten().copied().collect();
self.span_start
.filter(|span| serials.as_slice() == [span.serial])
.map(|span| (span.kind, span.serial))
}
fn unshown_rebuilt(&mut self, nested: &[u32]) {
let ids: Vec<u32> = nested
.iter()
.filter_map(|serial| self.document.revision_ids.get(serial))
.flatten()
.copied()
.collect();
if ids.is_empty() {
return;
}
if let Some(at) = self.paragraph
&& let Some(Item::Paragraph(paragraph)) = self.story().get_mut(at)
{
paragraph
.unshown
.retain(|(_, mark)| mark.id.is_none_or(|id| !ids.contains(&id)));
}
}
fn fix_mark(&mut self, paragraph: &mut Paragraph, mark: Option<(Kind, view_notes::Tag)>) {
paragraph.mark_fixed = true;
let Some((kind, tag)) = mark else {
return;
};
let serial = self.tag_serial(&tag);
paragraph.mark = Some(kind);
paragraph.mark_by = Some(serial);
}
fn label_use(&mut self, label: Label, level: u32, start: Option<u32>) -> Option<usize> {
if let Label::Text(text) = &label
&& text
.as_bytes()
.windows(2)
.any(|pair| pair[0] == b'%' && (b'1'..=b'9').contains(&pair[1]))
{
return None;
}
let labels = &mut self.document.labels;
let label = labels
.iter()
.position(|known| *known == label)
.unwrap_or_else(|| {
labels.push(label);
labels.len() - 1
});
let uses = &mut self.document.label_uses;
uses.push(LabelUse {
label,
level: level.min(8),
start,
});
Some(uses.len() - 1)
}
fn view_author(&self, handle: &str, date: Option<&str>) -> (String, String) {
let known = self.authors.get(handle);
let author = known.map_or_else(
|| {
if handle == view_notes::UNNAMED {
String::new()
} else {
handle.to_string()
}
},
|a| a.name.clone(),
);
let date = match (date, known) {
(Some(date), _) => date.to_string(),
(None, Some(known)) => known
.date
.as_ref()
.or(known.latest.as_ref())
.cloned()
.unwrap_or_else(|| {
known
.range
.as_ref()
.map(|(first, _)| format!("{first}T00:00:00Z"))
.unwrap_or_default()
}),
(None, None) => self.options.date.clone(),
};
(author, date)
}
fn box_boundary(&mut self, html: &str) -> bool {
if let Some(name) = html
.strip_prefix("<!-- text-box ")
.and_then(|s| s.strip_suffix(" -->"))
{
if !self.box_markdown.contains_key(name) {
return false;
}
self.end_paragraph();
let start = self.story().len();
self.box_open = Some((name.to_string(), self.target.clone(), start));
true
} else if html == "<!-- /text-box -->" {
self.end_paragraph();
if let Some((name, target, start)) = self.box_open.take() {
let end = self.story().len();
self.box_spans.push((name, target, start, end));
}
true
} else {
false
}
}
fn box_frames(&mut self) {
for (name, target, start, end) in std::mem::take(&mut self.box_spans).into_iter().rev() {
let Some((drawing, ordinal)) = name.rsplit_once('.') else {
continue;
};
let Some(index) = self.box_names.get(drawing).copied() else {
continue;
};
let Ok(ordinal) = ordinal.parse::<usize>() else {
continue;
};
if ordinal >= 4096 {
continue;
}
let items = match target {
Some(label) => self.definitions.get_mut(&label),
None => Some(&mut self.body),
};
let Some(items) = items.filter(|items| end <= items.len() && start <= end) else {
continue;
};
let mut items = items.drain(start..end).collect();
finish_story(&mut items);
let stories = self.document.box_stories.entry(index).or_default();
stories.resize_with(stories.len().max(ordinal + 1), Default::default);
stories[ordinal] = (self.box_markdown.remove(&name).unwrap_or_default(), items);
}
}
fn text_boxes(&mut self) {
let mut unplaced = std::mem::take(&mut self.unplaced);
let mut boxes: Vec<(usize, TextBox)> = Vec::new();
let mut spans: Vec<(usize, usize)> = Vec::new();
let mut at = 0;
while at < self.body.len() {
let Some(Item::Paragraph(paragraph)) = self.body.get(at) else {
at += 1;
continue;
};
at += 1;
let Some((inserted, mark)) = paragraph.unshown.first().cloned() else {
continue;
};
if paragraph.unshown.len() != 1 || paragraph.text_box.is_some() {
continue;
}
let Some(number) = paragraph.number else {
continue;
};
let end_of = self
.body
.iter()
.skip(at)
.position(|item| matches!(item, Item::ParagraphEnd))
.map_or(self.body.len(), |skip| at + skip);
let mut end = end_of + 1;
let mut content = Vec::new();
while let Some(item) = self.body.get(end) {
match item {
Item::Paragraph(named) if named.number.is_some() => break,
Item::Table { .. } => break,
Item::ParagraphEnd | Item::RowEnd | Item::Cell { .. } if content.is_empty() => {
break;
}
_ => {}
}
content.push(item.clone());
end += 1;
}
let holds_text = content
.iter()
.any(|item| matches!(item, Item::Paragraph(named) if named.number.is_none()));
if !holds_text {
continue;
}
let kind = if inserted { Kind::Insert } else { Kind::Delete };
let word = if inserted { "ins" } else { "del" };
let mut tags = unplaced
.remove(&number)
.unwrap_or_default()
.into_iter()
.filter(|(tagged, _)| *tagged == word)
.map(|(_, tag)| tag)
.collect::<Vec<_>>()
.into_iter();
for item in &mut content {
match item {
Item::Paragraph(boxed) => {
if let Some(tag) = tags.next() {
let serial = self.tag_serial(&tag);
boxed.mark = Some(kind);
boxed.mark_by = Some(serial);
boxed.mark_fixed = true;
}
}
Item::Run(run) => {
if let Some(tag) = tags.next() {
run.change = Some((kind, self.tag_serial(&tag)));
}
}
_ => {}
}
}
boxes.push((
at - 1,
TextBox {
inserted,
mark: mark.clone(),
items: content,
},
));
spans.push((end_of + 1, end));
}
for (at, boxed) in boxes {
if let Some(Item::Paragraph(paragraph)) = self.body.get_mut(at) {
paragraph.text_box = Some(boxed);
paragraph.unshown.clear();
}
}
for (start, end) in spans.into_iter().rev() {
if end > start {
self.body.drain(start..end);
}
}
self.unplaced = unplaced;
}
fn held_comment_marks(&mut self) {
let held: Vec<(usize, Kind, FormatMark, Vec<u32>)> = self
.body
.iter()
.enumerate()
.filter_map(|(at, item)| {
let Item::Paragraph(paragraph) = item else {
return None;
};
let [(inserted, mark)] = ¶graph.unshown[..] else {
return None;
};
let mut ids = Vec::new();
let leading = self.body[at + 1..]
.iter()
.take_while(|item| !matches!(item, Item::ParagraphEnd))
.map_while(|item| match item {
Item::CommentReference(id) => {
ids.push(*id);
Some(true)
}
Item::RangeStart(_) | Item::RangeEnd(_) => Some(true),
_ => None,
})
.count()
> 0;
let kind = if *inserted {
Kind::Insert
} else {
Kind::Delete
};
(leading && !ids.is_empty()).then_some((at, kind, mark.clone(), ids))
})
.collect();
for (at, kind, mark, ids) in held {
self.serial += 1;
let serial = self.serial;
self.document
.attributions
.insert(serial, (mark.author.clone(), mark.date.clone()));
if let Some(id) = mark.id {
self.name_revision(serial, vec![id]);
}
for id in ids {
self.document
.note_changes
.insert(id, ((kind, serial), false));
}
if let Some(Item::Paragraph(paragraph)) = self.body.get_mut(at) {
paragraph.unshown.clear();
}
}
}
fn place_held_events(&mut self) {
let ats: Vec<usize> = self
.body
.iter()
.enumerate()
.filter_map(|(at, item)| match item {
Item::Paragraph(paragraph) if !paragraph.holds.is_empty() => Some(at),
_ => None,
})
.collect();
for at in ats {
let Item::Paragraph(paragraph) = &self.body[at] else {
continue;
};
let holds = paragraph.holds.clone();
let mut at = at;
let mut end = self.body[at..]
.iter()
.position(|item| matches!(item, Item::ParagraphEnd))
.map_or(self.body.len(), |skip| at + skip);
let mut bound: HashMap<(bool, u32), Change> = HashMap::new();
for (inserted, revision, comment, event) in holds {
let Some(id) = self
.document
.comments
.iter()
.find(|row| row.number == Some(comment))
.map(|row| row.id)
else {
continue;
};
if !self.holds_event(at, end, id, event) {
let earlier = self.body[..at]
.iter()
.rposition(|item| matches!(item, Item::RangeEnd(e) if *e == id));
let reference = self.body[at..end]
.iter()
.position(|item| matches!(item, Item::CommentReference(r) if *r == id))
.map(|skip| at + skip);
let (1, Some(from), Some(to)) = (event, earlier, reference) else {
continue;
};
let item = self.body.remove(from);
at -= 1;
end -= 1;
self.body.insert(to - 1, item);
}
let key = (inserted, revision);
let change = bound.get(&key).copied().or_else(|| {
let change = self.held_revision(at, end, inserted, revision)?;
bound.insert(key, change);
Some(change)
});
if let Some(change) = change {
self.document.event_holds.insert((id, event), change);
}
}
self.gather_held_events(at, end);
}
}
fn holds_event(&self, start: usize, end: usize, id: u32, event: u8) -> bool {
self.body[start..end]
.iter()
.any(|item| match (item, event) {
(Item::RangeStart(slot), 0) => {
self.document.slots.get(*slot).copied().flatten() == Some(id)
}
(Item::RangeEnd(e), 1) | (Item::CommentReference(e), 2) => *e == id,
_ => false,
})
}
fn anchor_change(&self, item: &Item) -> Option<Change> {
let document = &self.document;
let (id, event) = match item {
Item::RangeStart(slot) => (document.slots.get(*slot).copied().flatten()?, 0),
Item::RangeEnd(id) => (*id, 1),
Item::CommentReference(id) => (*id, 2),
_ => return None,
};
document.event_holds.get(&(id, event)).copied().or_else(|| {
let (change, end_inside) = document.note_changes.get(&id)?;
match event {
1 if *end_inside => Some(*change),
2 => Some(*change),
_ => None,
}
})
}
fn gather_held_events(&mut self, start: usize, end: usize) {
let anchor = |item: &Item| {
matches!(
item,
Item::Bookmark(_)
| Item::RangeStart(_)
| Item::RangeEnd(_)
| Item::CommentReference(_)
)
};
let mut at = start;
while at < end {
if !anchor(&self.body[at]) {
at += 1;
continue;
}
let window = self.body[at..end]
.iter()
.take_while(|item| anchor(item))
.count();
let changes: Vec<Option<Change>> = self.body[at..at + window]
.iter()
.map(|item| self.anchor_change(item))
.collect();
if let Some(first) = changes.iter().position(Option::is_some) {
let change = changes[first];
if let Some(last) = changes.iter().rposition(|c| *c == change) {
let (loose, kept): (Vec<usize>, Vec<usize>) =
(first + 1..last).partition(|&i| {
changes[i].is_none() && matches!(self.body[at + i], Item::RangeStart(_))
});
if !loose.is_empty() {
let mut order: Vec<usize> = (0..first).collect();
order.extend(&loose);
order.push(first);
order.extend(kept);
order.extend(last..window);
let items: Vec<Item> =
order.iter().map(|&i| self.body[at + i].clone()).collect();
self.body.splice(at..at + window, items);
}
}
}
at += window;
}
}
fn held_revision(
&mut self,
start: usize,
end: usize,
inserted: bool,
revision: u32,
) -> Option<Change> {
let kind = if inserted { Kind::Insert } else { Kind::Delete };
let runs: Vec<u32> = self.body[start..end]
.iter()
.filter_map(|item| match item {
Item::Run(run) => run
.change
.filter(|(own, _)| *own == kind)
.map(|(_, serial)| serial),
_ => None,
})
.collect();
for serial in runs {
if self
.document
.revision_ids
.get(&serial)
.is_some_and(|ids| ids.contains(&revision))
{
return Some((kind, serial));
}
}
let here: HashSet<u32> = self.body[start..end]
.iter()
.filter_map(|item| match item {
Item::CommentReference(id) => Some(*id),
_ => None,
})
.collect();
let noted: Vec<Change> = self
.document
.note_changes
.iter()
.filter(|(comment, _)| here.contains(comment))
.map(|(_, (change, _))| *change)
.filter(|(own, _)| *own == kind)
.collect();
for change in noted {
if self
.document
.revision_ids
.get(&change.1)
.is_some_and(|ids| ids.contains(&revision))
{
return Some(change);
}
}
let Item::Paragraph(paragraph) = self.body.get_mut(start)? else {
return None;
};
let found = paragraph
.unshown
.iter()
.position(|(ins, mark)| *ins == inserted && mark.id == Some(revision))?;
let (_, mark) = paragraph.unshown.remove(found);
self.serial += 1;
let serial = self.serial;
self.document
.attributions
.insert(serial, (mark.author, mark.date));
self.name_revision(serial, vec![revision]);
Some((kind, serial))
}
fn named_held_marks(&mut self) {
let mut bound: HashMap<(usize, Vec<u32>), (Kind, u32)> = HashMap::new();
let mut paragraphs = Vec::new();
for (comment, number, ids) in std::mem::take(&mut self.held_in) {
let reference = self
.body
.iter()
.position(|item| matches!(item, Item::CommentReference(id) if *id == comment));
let start = reference.and_then(|at| {
self.body[..at]
.iter()
.rposition(|item| matches!(item, Item::Paragraph(_)))
});
let (Some(at), Some(start)) = (reference, start) else {
continue;
};
let end = self.body[at..]
.iter()
.position(|item| matches!(item, Item::ParagraphEnd))
.map_or(self.body.len(), |skip| at + skip);
let change = bound.get(&(start, ids.clone())).copied().or_else(|| {
self.body[start..end].iter().find_map(|item| match item {
Item::Run(run) => run.change.filter(|(_, serial)| {
self.document
.revision_ids
.get(serial)
.is_some_and(|named| ids.iter().all(|id| named.contains(id)))
}),
_ => None,
})
});
let change = change.or_else(|| {
let &[id] = ids.as_slice() else {
return None;
};
let Some(Item::Paragraph(paragraph)) = self.body.get_mut(start) else {
return None;
};
let found = paragraph
.unshown
.iter()
.position(|(_, mark)| mark.id == Some(id))?;
let (inserted, mark) = paragraph.unshown.remove(found);
self.serial += 1;
let serial = self.serial;
self.document
.attributions
.insert(serial, (mark.author, mark.date));
self.name_revision(serial, vec![id]);
Some((if inserted { Kind::Insert } else { Kind::Delete }, serial))
});
let Some(change) = change else {
self.document.warnings.push(format!(
"c{number} is in {}, which its paragraph does not have: its mark stays after its text",
held_tag(&ids)
));
continue;
};
bound.insert((start, ids), change);
self.document.note_changes.insert(comment, (change, false));
paragraphs.push(start);
}
for start in paragraphs {
self.gather_held_references(start);
}
}
fn gather_held_references(&mut self, start: usize) {
let notes = &self.document.note_changes;
let held = |item: &Item| match item {
Item::CommentReference(id) => notes.get(id).filter(|(_, end)| !end).map(|(c, _)| *c),
_ => None,
};
let mut at = start;
while at < self.body.len() && !matches!(self.body[at], Item::ParagraphEnd) {
let Some(change) = held(&self.body[at]) else {
at += 1;
continue;
};
let window = self.body[at..]
.iter()
.take_while(|item| matches!(item, Item::RangeEnd(_)) || held(item) == Some(change))
.count();
let last = self.body[at..at + window]
.iter()
.rposition(|item| held(item) == Some(change))
.map_or(at, |skip| at + skip);
let (ends, references): (Vec<Item>, Vec<Item>) = self.body[at..=last]
.iter()
.cloned()
.partition(|item| matches!(item, Item::RangeEnd(_)));
let count = last + 1 - at;
self.body
.splice(at..=last, ends.into_iter().chain(references));
at += count;
}
}
fn finish(mut self) -> Document {
self.end_paragraph();
self.textless_paragraph();
self.settle_guessed_wraps();
if let Some(comment) = self.comment.take() {
self.document.comments.push(comment);
}
for name in self
.document
.drawings
.iter()
.flat_map(|drawing| drawing.nested_tokens())
{
let error = if !self.box_names.contains_key(&name) {
Some(format!(
"text-box {name}: nested drawing token is missing; deleting the box token is unsupported"
))
} else if self.box_duplicates.contains(&name) {
Some(format!(
"text-box {name}: nested drawing token appears more than once"
))
} else {
None
};
if let Some(error) = error {
self.document.box_error.get_or_insert(error);
}
}
for (name, &index) in &self.box_names {
if let Some(drawing) = self.document.drawings.get(index)
&& let Err(error) = drawing.check_box_regions(name, &self.box_markdown)
{
self.document.box_error.get_or_insert(error);
}
}
for name in self.box_markdown.keys() {
let resolved = name.rsplit_once('.').and_then(|(token, ordinal)| {
let index = *self.box_names.get(token)?;
let ordinal = ordinal.parse::<usize>().ok()?;
self.document
.drawings
.get(index)
.map(|drawing| ordinal < drawing.box_count())
});
let reason = match resolved {
None => "undefined or absent drawing token",
Some(false) => "box index out of range",
Some(true) => continue,
};
self.document
.box_error
.get_or_insert_with(|| format!("text-box {name}: {reason}"));
}
self.box_frames();
self.text_boxes();
self.named_held_marks();
self.held_comment_marks();
self.place_held_events();
let mut body = std::mem::take(&mut self.body);
clear_continued_marks(&mut body, &self.document);
finish_story(&mut body);
let targets: HashSet<&str> = body
.iter()
.chain(self.definitions.values().flatten())
.filter_map(|item| match item {
Item::LinkStart(Link::Anchor(name), _) => Some(name.as_str()),
_ => None,
})
.collect();
let anchors: HashSet<&str> = body
.iter()
.chain(self.definitions.values().flatten())
.filter_map(|item| match item {
Item::Bookmark(name) => Some(name.as_str()),
_ => None,
})
.collect();
let to_headings: HashSet<&str> = targets.difference(&anchors).copied().collect();
let headings = heading_bookmarks(&body, &to_headings);
let landed: HashSet<String> = headings
.iter()
.flat_map(|(_, _, named)| named.iter().cloned())
.chain(anchors.iter().map(|name| (*name).to_string()))
.collect();
let mut missing: Vec<&str> = targets
.iter()
.copied()
.filter(|name| !landed.contains(*name))
.collect();
missing.sort_unstable();
for name in missing {
self.document.warnings.push(format!(
"link to #{name} names no heading: Word writes it, but it leads nowhere"
));
}
let mut renamed: HashMap<String, String> = HashMap::new();
let mut used: HashSet<String> = headings
.iter()
.filter(|(_, slug, _)| word_takes(slug))
.map(|(_, slug, _)| slug.clone())
.chain(anchors.iter().map(|name| (*name).to_string()))
.collect();
for (at, slug, named) in headings {
let name = bookmark_name(&slug, &used);
if name != slug {
used.insert(name.clone());
}
for target in named.into_iter().chain([slug]) {
if target != name {
renamed.entry(target).or_insert_with(|| name.clone());
}
}
if let Item::Paragraph(paragraph) = &mut body[at] {
paragraph.bookmark = Some(name);
}
}
if !renamed.is_empty() {
for item in body
.iter_mut()
.chain(self.definitions.values_mut().flatten())
{
if let Item::LinkStart(Link::Anchor(anchor), _) = item
&& let Some(name) = renamed.get(anchor.as_str())
{
anchor.clone_from(name);
}
}
}
self.document.body = body;
let mut shared: Vec<(&String, &usize)> = self
.label_definitions
.iter()
.filter(|(_, count)| **count > 1)
.collect();
shared.sort();
for (label, &count) in shared {
let uses = self.label_uses.get(label).copied().unwrap_or(0);
self.document.warnings.push(if uses >= count {
format!(
"[^{label}] is defined {count} times: its first {count} references name \
them in order, each written as a note of its own"
)
} else {
format!(
"[^{label}] is defined {count} times but referenced {uses}: the \
definitions past the {uses} its references name are dropped"
)
});
}
for (label, change) in std::mem::take(&mut self.references) {
let endnote = self.endnotes.contains(&label);
let (text, reference) = if endnote {
("EndnoteText", "EndnoteReference")
} else {
("FootnoteText", "FootnoteReference")
};
self.document.styles.insert(text);
self.document.styles.insert(reference);
let mut items = self.definitions.get(&label).cloned().unwrap_or_default();
if items.is_empty() {
items = vec![Item::Paragraph(Paragraph {
style: Some(text.into()),
..Paragraph::default()
})];
items.push(Item::ParagraphEnd);
}
let clauses = self.note_clauses.remove(&label).unwrap_or_default();
let wrapped = has_changes(&items);
if let Some((kind, serial)) = change
&& !wrapped
&& !self.view
{
mark_whole(&mut items, kind, serial);
}
let mut change = change.filter(|(kind, _)| only_changed_by(&items, *kind));
let own: Vec<view_notes::Tag> = if clauses.rev.len() == paragraphs(&items)
&& clauses.rev.iter().all(|(_, tag)| tag.ids.len() > 1)
{
clauses
.rev
.iter()
.flat_map(|(_, tag)| {
let (text, mark) = tag.ids.split_at(tag.ids.len() - 1);
[mark, text].map(|ids| view_notes::Tag {
ids: ids.to_vec(),
..tag.clone()
})
})
.collect()
} else {
clauses.rev.iter().map(|(_, tag)| tag.clone()).collect()
};
if let Some((kind, _)) = change
&& !self.resolved
&& in_one_change(&items, kind)
&& own.len() == paragraphs(&items)
{
let serials = self.note_serials(&label, &own);
let mut next = serials.iter().copied();
let mut runs = None;
for item in &mut items {
match item {
Item::Paragraph(_) => runs = next.next(),
Item::Run(run) => run.change = runs.map(|serial| (kind, serial)),
_ => {}
}
}
change = serials.first().map(|&first| (kind, first));
} else if let Some((kind, _)) = change
&& !self.resolved
&& in_one_change(&items, kind)
&& own.len() == 2 * paragraphs(&items)
{
let serials = self.note_serials(&label, &own);
own_note_marks(&mut items, kind, &serials);
change = serials.get(1).map(|&first| (kind, first));
} else if let Some((kind, _)) = change
&& wrapped
&& clauses.rev.is_empty()
&& in_one_change(&items, kind)
{
for item in &mut items {
match item {
Item::Run(run) => run.change = None,
Item::Paragraph(paragraph) => {
paragraph.mark = None;
paragraph.mark_by = None;
}
_ => {}
}
}
change = None;
} else if !self.resolved
&& let Some(Item::Paragraph(last)) = items
.iter_mut()
.rev()
.find(|item| matches!(item, Item::Paragraph(_)))
{
let mut unshown = Vec::new();
for (inserted, tag) in &clauses.rev {
let marks = self.unshown_marks(tag);
unshown.extend(marks.into_iter().map(|mark| (*inserted, mark)));
}
last.unshown = unshown;
}
if !clauses.fmt.is_empty()
&& let Some(Item::Paragraph(first)) = items.first_mut()
{
first.formats = clauses
.fmt
.iter()
.map(|tag| self.format_mark(tag))
.collect();
}
finish_story(&mut items);
self.document.notes.push(Note {
items,
change,
endnote,
});
}
self.share_pooled_ids();
self.share_substitution_ids();
self.range_ends();
self.comments_out_of_notes();
renumber_comments(&mut self.document);
self.document
}
fn range_ends(&mut self) {
let mut ranged = std::mem::take(&mut self.ranged);
let mut comments = std::mem::take(&mut self.ranged_comments);
let mut handles: BTreeSet<String> = ranged.keys().cloned().collect();
handles.extend(
self.authors
.iter()
.filter(|(_, known)| known.range.is_some())
.map(|(handle, _)| handle.clone()),
);
for handle in handles {
let serials = ranged.remove(&handle).unwrap_or_default();
let undated = comments.remove(&handle).unwrap_or_default();
if self.range_ended.contains(&handle) {
continue;
}
let Some((name, first, last)) = self.authors.get(&handle).and_then(|known| {
let (first, last) = known.range.as_ref()?;
Some((
known.name.clone(),
first.clone(),
format!("{last}T23:59:59Z"),
))
}) else {
continue;
};
let last_day = &last[..first.len()];
let outside = self
.document
.attributions
.values()
.chain(self.document.comments.iter().filter_map(|c| c.by.as_ref()))
.filter(|(author, _)| *author == name)
.filter_map(|(_, date)| date.get(..first.len()))
.find(|day| *day < first.as_str() || *day > last_day)
.map(str::to_string);
if let Some(day) = outside {
self.document.warnings.push(format!(
"authors: {handle}: a tag dated {day} falls outside {first}..{last_day}, \
so the days read back wider"
));
}
let on_first = |date: &str| date.starts_with(first.as_str());
let firsts = self
.document
.attributions
.values()
.filter(|(author, date)| *author == name && on_first(date))
.count()
+ self
.document
.comments
.iter()
.filter(|comment| {
comment
.by
.as_ref()
.is_some_and(|(author, date)| *author == name && on_first(date))
})
.count();
let marks: usize = serials
.iter()
.map(|s| {
self.document
.revision_ids
.get(s)
.map_or(1, |ids| ids.len().max(1))
})
.sum();
let comment = undated.last().and_then(|id| {
self.document
.comments
.iter()
.position(|comment| comment.id == *id)
});
if let Some(at) = comment
&& (firsts > 1 || marks > 0)
{
if let Some((_, date)) = &mut self.document.comments[at].by {
date.clone_from(&last);
}
} else if let Some(&serial) = serials.last()
&& (marks > 1 || firsts > 1)
{
let ids = self.document.revision_ids.get(&serial).cloned();
for &same in &serials {
if same == serial
|| ids.as_ref().is_some_and(|ids| {
!ids.is_empty() && self.document.revision_ids.get(&same) == Some(ids)
})
{
self.document.range_ends.insert(same, last.clone());
}
}
} else if firsts + marks > 0 {
if let Some(person) = self.document.people.get_mut(&handle) {
person.1 = last;
}
} else {
self.document.story_range_ends.insert(handle, last);
}
}
}
}
const MOST_BOOKMARK: usize = 40;
fn word_takes(slug: &str) -> bool {
slug.starts_with(char::is_alphabetic) && slug.chars().count() <= MOST_BOOKMARK
}
pub(super) fn bookmark_name(slug: &str, used: &HashSet<String>) -> String {
if word_takes(slug) {
return slug.to_string();
}
let slug = if slug.starts_with(char::is_alphabetic) {
Cow::Borrowed(slug)
} else {
Cow::Owned(format!("_{slug}"))
};
if slug.chars().count() <= MOST_BOOKMARK && !used.contains(slug.as_ref()) {
return slug.into_owned();
}
(0..)
.map(|n| {
let suffix = if n == 0 {
String::new()
} else {
format!("-{n}")
};
let head: String = slug.chars().take(MOST_BOOKMARK - suffix.len()).collect();
head + &suffix
})
.find(|name| !used.contains(name))
.unwrap_or_default()
}
pub(super) fn is_bookmark_of(name: &str, slug: &str) -> bool {
if name == slug || name == bookmark_name(slug, &HashSet::new()) {
return true;
}
if word_takes(slug) {
return false;
}
let slug = if slug.starts_with(char::is_alphabetic) {
Cow::Borrowed(slug)
} else {
Cow::Owned(format!("_{slug}"))
};
name.rsplit_once('-').is_some_and(|(head, n)| {
!n.starts_with('0')
&& n.parse::<u32>().is_ok_and(|n| n > 0)
&& head
.chars()
.eq(slug.chars().take(MOST_BOOKMARK.saturating_sub(n.len() + 1)))
})
}
pub(super) fn github_slug(text: &str) -> String {
text.to_lowercase()
.chars()
.filter_map(|c| match c {
' ' => Some('-'),
'-' => Some(c),
c if c.is_alphabetic() => Some(c),
c => match c.general_category_group() {
GeneralCategoryGroup::Letter | GeneralCategoryGroup::Mark => Some(c),
GeneralCategoryGroup::Number
if c.general_category() != GeneralCategory::OtherNumber =>
{
Some(c)
}
GeneralCategoryGroup::Punctuation
if c.general_category() == GeneralCategory::ConnectorPunctuation =>
{
Some(c)
}
_ => None,
},
})
.collect()
}
#[derive(Default)]
pub(super) struct Slugger {
seen: HashMap<String, usize>,
}
impl Slugger {
pub(super) fn name(&mut self, slug: &str) -> String {
let mut name = slug.to_string();
while self.seen.contains_key(&name) {
let repeats = self.seen.entry(slug.to_string()).or_insert(0);
*repeats += 1;
name = format!("{slug}-{repeats}");
}
self.seen.insert(name.clone(), 0);
name
}
}
fn heading_bookmarks(body: &[Item], targets: &HashSet<&str>) -> Vec<(usize, String, Vec<String>)> {
let mut found = Vec::new();
if targets.is_empty() {
return found;
}
let mut slugger = Slugger::default();
for (at, item) in body.iter().enumerate() {
let Item::Paragraph(paragraph) = item else {
continue;
};
if !paragraph.heading {
continue;
}
let text: String = body[at + 1..]
.iter()
.take_while(|item| !matches!(item, Item::ParagraphEnd))
.filter_map(|item| match item {
Item::Run(Run {
content: Content::Text(text),
change,
..
}) if !matches!(change, Some((Kind::Delete, _))) => Some(text.as_str()),
_ => None,
})
.collect();
let slug = github_slug(&text);
let name = slugger.name(&slug);
if slug.is_empty() {
continue;
}
let mut named: Vec<String> = targets
.iter()
.filter(|target| is_bookmark_of(target, &name))
.map(|target| (*target).to_string())
.collect();
if !named.is_empty() {
named.sort_unstable();
found.push((at, name, named));
}
}
found
}
fn mark_ids(tags: &[view_notes::Tag], serials: usize) -> Vec<Vec<u32>> {
match tags {
[] => Vec::new(),
[tag] => (0..serials)
.map(|i| match i.cmp(&(serials - 1)) {
std::cmp::Ordering::Less => tag.ids.get(i).copied().into_iter().collect(),
_ => tag.ids.get(i..).map(<[u32]>::to_vec).unwrap_or_default(),
})
.collect(),
tags => (0..serials)
.map(|i| tags[i.min(tags.len() - 1)].ids.clone())
.collect(),
}
}
impl Writer<'_, '_> {
fn share_pooled_ids(&mut self) {
let pools: Vec<(Vec<u32>, Vec<u32>)> = std::mem::take(&mut self.pools)
.into_iter()
.filter(|(_, (notes, _))| *notes > 1)
.map(|((_, ids), (_, serials))| (ids, serials))
.collect();
if pools.is_empty() {
return;
}
let mut pool_of: HashMap<u32, usize> = HashMap::new();
for (at, (_, serials)) in pools.iter().enumerate() {
for &serial in serials {
pool_of.insert(serial, at);
}
}
let none = vec![0; pools.len()];
let spare_of = |counts: &[usize]| -> Vec<usize> {
pools
.iter()
.zip(counts)
.map(|((ids, _), &count)| ids.len().saturating_sub(count))
.collect()
};
let (_, fewest) = self.pool_pieces(&pool_of, &vec![false; pools.len()], &none, &none);
let spare = spare_of(&fewest);
let (_, apart) = self.pool_pieces(&pool_of, &vec![true; pools.len()], &spare, &none);
let split: Vec<bool> = pools
.iter()
.zip(&apart)
.map(|((ids, _), &count)| ids.len() >= count)
.collect();
let (_, after) = self.pool_pieces(&pool_of, &split, &spare, &none);
let (piece, pieces) = self.pool_pieces(&pool_of, &split, &spare, &spare_of(&after));
for (pool, (ids, serials)) in pools.iter().enumerate() {
let count = pieces[pool];
for serial in serials {
let Some(&at) = piece.get(serial) else {
continue;
};
let Some(&id) = ids.get(at).or(ids.last()) else {
continue;
};
let mut own = vec![id];
if at + 1 == count {
own.extend(ids.iter().skip(count));
}
self.document.revision_ids.insert(*serial, own);
}
}
self.shared_tags.retain(|(deleted, inserted)| {
!piece.contains_key(deleted) && !piece.contains_key(inserted)
});
}
fn pool_pieces(
&self,
pool_of: &HashMap<u32, usize>,
split: &[bool],
spare: &[usize],
spare_nests: &[usize],
) -> (HashMap<u32, usize>, Vec<usize>) {
let mut pieces = vec![0usize; split.len()];
let mut current: Vec<Option<(usize, Option<Kind>)>> = vec![None; split.len()];
let mut spent = vec![0usize; split.len()];
let mut spent_nests = vec![0usize; split.len()];
let mut piece: HashMap<u32, usize> = HashMap::new();
let notes = self.document.notes.iter().map(|note| ¬e.items);
for items in std::iter::once(&self.document.body).chain(notes) {
let mut before: Vec<(usize, bool)> = Vec::new();
let mut mark = None;
for item in items {
match item {
Item::Run(run) => {
let mut now = Vec::new();
let mut placed: Vec<(usize, usize)> = Vec::new();
let mut chain: Vec<Change> = run.change.into_iter().collect();
while let Some(&outer) =
chain.last().and_then(|(_, by)| self.document.wraps.get(by))
&& !chain.iter().any(|&(_, by)| by == outer.1)
{
chain.push(outer);
}
for (depth, (kind, serial)) in chain.into_iter().enumerate() {
let Some(&pool) = pool_of.get(&serial) else {
continue;
};
let nested = depth > 0;
let at = *piece.entry(serial).or_insert_with(|| {
let mut goes_on = false;
let mut after_nest = false;
let mut after_piece = false;
for &(other, inside) in &before {
if other == pool {
goes_on |= nested != inside || (nested && !split[pool]);
after_nest |= !nested && inside;
after_piece |= nested && !inside;
}
}
let goes_on = current[pool]
.filter(|&(_, was)| goes_on && was == Some(kind))
.map(|(at, _)| at);
match goes_on {
Some(_) if after_nest && spent[pool] < spare[pool] => {
spent[pool] += 1;
pieces[pool] += 1;
pieces[pool] - 1
}
Some(_)
if after_piece && spent_nests[pool] < spare_nests[pool] =>
{
spent_nests[pool] += 1;
pieces[pool] += 1;
pieces[pool] - 1
}
Some(at) => at,
None => {
pieces[pool] += 1;
pieces[pool] - 1
}
}
});
current[pool] = Some((at, Some(kind)));
now.push((pool, nested));
placed.push((pool, at));
}
if let Content::Drawing(index) = &run.content {
let boxes = self.document.box_stories.get(index);
for item in boxes.into_iter().flatten().flat_map(|(_, items)| items) {
if let Item::Run(Run {
change: Some((_, serial)),
..
}) = item
&& let Some(pool) = pool_of.get(serial)
&& let Some(&(_, at)) = placed.iter().find(|(p, _)| p == pool)
{
piece.entry(*serial).or_insert(at);
}
}
}
before = now;
}
Item::Bookmark(_)
| Item::RangeStart(_)
| Item::RangeEnd(_)
| Item::CommentReference(_)
| Item::LinkStart(..)
| Item::LinkEnd => {}
Item::Paragraph(paragraph) => {
mark = paragraph.mark_by;
before.clear();
}
Item::ParagraphEnd => {
if let Some(serial) = mark.take()
&& let Some(&pool) = pool_of.get(&serial)
&& !piece.contains_key(&serial)
{
piece.insert(serial, pieces[pool]);
current[pool] = Some((pieces[pool], None));
pieces[pool] += 1;
}
before.clear();
}
_ => before.clear(),
}
}
}
(piece, pieces)
}
fn share_substitution_ids(&mut self) {
let mut runs: HashMap<u32, usize> = HashMap::new();
let notes = self.document.notes.iter().flat_map(|note| ¬e.items);
for item in self.document.body.iter().chain(notes) {
if let Item::Run(Run {
change: Some((_, by)),
..
}) = item
{
*runs.entry(*by).or_default() += 1;
}
}
for (deleted, inserted) in std::mem::take(&mut self.shared_tags) {
let ids = &mut self.document.revision_ids;
let mut all = ids.get(&deleted).cloned().unwrap_or_default();
all.extend(ids.get(&inserted).cloned().unwrap_or_default());
if all.len() < 3 {
continue;
}
let drop = all.windows(2).position(|pair| pair[1] < pair[0]);
let pieces = drop.map_or_else(|| runs.get(&deleted).copied().unwrap_or(1), |at| at + 1);
let cut = pieces.clamp(1, all.len() - 1);
let rest = all.split_off(cut);
ids.insert(deleted, all);
ids.insert(inserted, rest);
}
}
}
fn held_tag(ids: &[u32]) -> String {
let ids: Vec<String> = ids.iter().map(u32::to_string).collect();
format!("r{}", ids.join("+"))
}
fn renumber_comments(document: &mut Document) {
let mut taken = HashSet::new();
let claimed: Vec<Option<u32>> = document
.comments
.iter()
.map(|c| c.number.filter(|&n| taken.insert(n)))
.collect();
let mut next = 0u32;
let mut ids = HashMap::new();
for (comment, claimed) in document.comments.iter().zip(&claimed) {
let id = claimed.unwrap_or_else(|| {
while taken.contains(&next) {
next += 1;
}
taken.insert(next);
next
});
ids.insert(comment.id, id);
}
let numbered: HashSet<u32> = claimed.iter().flatten().copied().collect();
for comment in &mut document.comments {
comment.id = ids[&comment.id];
comment.parent = comment
.parent
.filter(|p| numbered.contains(p) && *p != comment.id);
}
for id in document
.slots
.iter_mut()
.flatten()
.chain(document.shared.values_mut().flatten())
{
*id = ids[id];
}
let notes = document
.notes
.iter_mut()
.flat_map(|note| note.items.iter_mut());
for item in document.body.iter_mut().chain(notes) {
if let Item::RangeEnd(id) | Item::CommentReference(id) = item {
*id = ids[id];
}
}
document.note_changes = std::mem::take(&mut document.note_changes)
.into_iter()
.map(|(id, change)| (ids[&id], change))
.collect();
document.event_holds = std::mem::take(&mut document.event_holds)
.into_iter()
.map(|((id, event), change)| ((ids[&id], event), change))
.collect();
}
fn clear_continued_marks(items: &mut [Item], document: &Document) {
let mut paragraphs: HashMap<u32, HashSet<usize>> = HashMap::new();
let mut at = 0usize;
for item in items.iter() {
match item {
Item::Paragraph(paragraph) => {
at += 1;
if let Some(serial) = paragraph.mark_by {
paragraphs.entry(serial).or_default().insert(at);
}
}
Item::Run(run) => {
if let Some((_, serial)) = run.change {
paragraphs.entry(serial).or_default().insert(at);
}
}
_ => {}
}
}
for (inner, (_, outer)) in document.wraps.iter() {
if let Some(ats) = paragraphs.get(inner).cloned() {
paragraphs.entry(*outer).or_default().extend(ats);
}
}
let continued = |serial: u32, at: usize| {
document.revision_ids.get(&serial).is_some_and(|ids| {
document.revision_ids.iter().any(|(other, named)| {
*other != serial
&& named.iter().any(|id| ids.contains(id))
&& paragraphs
.get(other)
.is_some_and(|serials| serials.iter().any(|p| *p != at))
})
})
};
let mut at = 0usize;
for item in items.iter_mut() {
let Item::Paragraph(paragraph) = item else {
continue;
};
at += 1;
if !paragraph.mark_fixed
&& paragraph
.mark_by
.is_some_and(|serial| continued(serial, at))
{
paragraph.mark = None;
paragraph.mark_by = None;
paragraph.whole = false;
}
}
}
fn finish_story(items: &mut Vec<Item>) {
if matches!(items.last(), Some(Item::TableEnd)) {
let start = items
.iter()
.rposition(|item| matches!(item, Item::Table { .. }))
.unwrap_or(0);
let mut rows = items[start..].iter().filter_map(|item| match item {
Item::Row { change, .. } => Some(*change),
_ => None,
});
let first = rows.next().flatten();
let change = first
.filter(|(kind, _)| rows.all(|change| change.is_some_and(|(other, _)| other == *kind)));
items.push(Item::Paragraph(Paragraph {
mark: change.map(|(kind, _)| kind),
mark_by: change.map(|(_, serial)| serial),
whole: change.is_some(),
..Paragraph::default()
}));
items.push(Item::ParagraphEnd);
}
let mut depth = 0usize;
let mut last: Option<usize> = None;
for index in (0..items.len()).rev() {
match &items[index] {
Item::TableEnd => depth += 1,
Item::Table { .. } => depth = depth.saturating_sub(1),
Item::Paragraph(paragraph) if depth == 0 => match last {
None => {
if !(paragraph.whole && paragraph.mark.is_some()) {
return;
}
last = Some(index);
}
Some(at) => {
let (kind, by) = match &mut items[at] {
Item::Paragraph(ending) => {
ending.whole = false;
(ending.mark.take(), ending.mark_by.take())
}
_ => (None, None),
};
let Item::Paragraph(before) = &mut items[index] else {
return;
};
if before.mark_fixed {
} else if before.mark.is_none() {
before.mark = kind;
before.mark_by = by;
} else if before.whole && before.mark == kind {
let earlier = items[..index].iter().rposition(|item| match item {
Item::Paragraph(p) => !(p.whole && p.mark == kind),
_ => false,
});
if let Some(earlier) = earlier
&& let Item::Paragraph(p) = &mut items[earlier]
&& p.mark.is_none()
&& !p.mark_fixed
{
p.mark = kind;
p.mark_by = by;
}
} else if before.whole && before.mark != kind && at == end_of(items, index) + 1
{
let content: Vec<Item> = items.drain(index + 1..at - 1).collect();
items.drain(index..index + 2);
let last = index;
items.splice(last + 1..last + 1, content);
}
return;
}
},
_ => {}
}
}
if let Some(at) = last
&& let Item::Paragraph(only) = &mut items[at]
{
only.mark = None;
only.mark_by = None;
only.whole = false;
}
}
fn other(kind: Kind) -> Kind {
match kind {
Kind::Insert => Kind::Delete,
Kind::Delete => Kind::Insert,
}
}
fn attribution(text: &str) -> Option<(Option<String>, &str)> {
match named(text)? {
(author, date, "") => Some((author, date)),
_ => None,
}
}
#[doc(hidden)]
pub fn named(text: &str) -> Option<(Option<String>, &str, &str)> {
let mut from = 0;
while let Some(open) = text[from..].find('(').map(|at| from + at) {
from = open + 1;
let Some(close) = text[open..].find(')').map(|at| open + at) else {
continue;
};
let date = &text[open + 1..close];
if !is_date(date) {
continue;
}
let name = &text[..open];
let author = match name.trim() {
"" if name.is_empty() => None,
"" => return None,
author if name.ends_with(' ') => Some(unescaped(author).to_string()),
_ => continue,
};
let mut depth = 0i64;
let mut unbalanced = false;
for c in text[..open].chars() {
match c {
'(' => depth += 1,
')' => {
depth -= 1;
unbalanced |= depth < 0;
}
_ => {}
}
}
if unbalanced || depth != 0 {
return None;
}
return Some((author, date, &text[close + 1..]));
}
None
}
pub(super) fn unescaped(name: &str) -> String {
let mut out = String::with_capacity(name.len());
let mut rest = name;
while let Some(at) = rest.find('%') {
out.push_str(&rest[..at]);
let spelled = match rest.get(at + 1..at + 3) {
Some("20") => Some(' '),
Some("25") => Some('%'),
Some("28") => Some('('),
Some("29") => Some(')'),
Some("5C") | Some("5c") => Some('\\'),
_ => None,
};
match spelled {
Some(c) => out.push(c),
None => out.push('%'),
}
rest = &rest[at + 1 + usize::from(spelled.is_some()) * 2..];
}
out.push_str(rest);
out
}
pub(super) fn is_date(text: &str) -> bool {
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let Some((day_text, time)) = text.split_once('T') else {
return false;
};
let day: Vec<&str> = day_text.split('-').collect();
if day.len() != 3
|| day[0].len() != 4
|| day[1..].iter().any(|p| p.len() != 2)
|| !day.iter().all(|p| digits(p))
{
return false;
}
let (clock_text, zone) = match time.find(['Z', '+', '-']) {
Some(at) => time.split_at(at),
None => (time, ""),
};
let zone_ok = match zone {
"" | "Z" => true,
zone => {
let offset = &zone[1..];
offset.len() == 5
&& offset.as_bytes()[2] == b':'
&& digits(&offset[..2])
&& digits(&offset[3..])
}
};
let clock: Vec<&str> = clock_text.split(':').collect();
let seconds_ok = clock.get(2).is_none_or(|seconds| {
let (whole, fraction) = seconds.split_once('.').unwrap_or((seconds, "0"));
whole.len() == 2 && digits(whole) && digits(fraction)
});
let shaped = zone_ok
&& (2..=3).contains(&clock.len())
&& clock[..2].iter().all(|p| p.len() == 2 && digits(p))
&& seconds_ok;
let seconds = if clock.len() == 2 { ":00" } else { "" };
shaped
&& crate::util::datetime::parse_datetime(&format!("{day_text}T{clock_text}{seconds}{zone}"))
.is_ok()
}
fn no_table_between(items: &[Item], from: usize, to: usize) -> bool {
!items[from..to]
.iter()
.any(|item| matches!(item, Item::Table { .. } | Item::TableEnd))
}
fn end_of(items: &[Item], start: usize) -> usize {
items[start..]
.iter()
.position(|item| matches!(item, Item::ParagraphEnd))
.map_or(items.len(), |offset| start + offset)
}
fn only_changed_by(items: &[Item], kind: Kind) -> bool {
items.iter().all(|item| match item {
Item::Run(run) => run.change.is_some_and(|(k, _)| k == kind),
_ => true,
})
}
fn in_one_change(items: &[Item], kind: Kind) -> bool {
let last = items
.iter()
.rposition(|item| matches!(item, Item::Paragraph(_)));
let mut serial = None;
items.iter().enumerate().all(|(index, item)| {
let change = match item {
Item::Run(run) => run.change,
Item::Paragraph(paragraph) if Some(index) != last => {
paragraph.mark.zip(paragraph.mark_by)
}
_ => return true,
};
change.is_some_and(|(own, by)| own == kind && *serial.get_or_insert(by) == by)
})
}
fn paragraphs(items: &[Item]) -> usize {
items
.iter()
.filter(|item| matches!(item, Item::Paragraph(_)))
.count()
}
fn own_note_marks(items: &mut [Item], kind: Kind, serials: &[u32]) {
let mut next = serials.iter().copied();
let mut runs = None;
for item in items {
match item {
Item::Paragraph(paragraph) => {
paragraph.mark = Some(kind);
paragraph.mark_by = next.next();
paragraph.mark_fixed = true;
runs = next.next();
}
Item::Run(run) => run.change = runs.map(|serial| (kind, serial)),
_ => {}
}
}
}
fn has_changes(items: &[Item]) -> bool {
items.iter().any(|item| match item {
Item::Run(run) => run.change.is_some(),
Item::Paragraph(paragraph) => paragraph.mark.is_some(),
_ => false,
})
}
fn mark_whole(items: &mut [Item], kind: Kind, serial: u32) {
let last = items
.iter()
.rposition(|item| matches!(item, Item::Paragraph(_)));
for (index, item) in items.iter_mut().enumerate() {
match item {
Item::Run(run) => run.change = Some((kind, serial)),
Item::Paragraph(paragraph) if Some(index) != last => {
paragraph.mark = Some(kind);
paragraph.mark_by = Some(serial);
}
_ => {}
}
}
}
fn heading_level(level: HeadingLevel) -> usize {
match level {
HeadingLevel::H1 => 1,
HeadingLevel::H2 => 2,
HeadingLevel::H3 => 3,
HeadingLevel::H4 => 4,
HeadingLevel::H5 => 5,
HeadingLevel::H6 => 6,
}
}
fn alignment(alignment: Alignment) -> Option<&'static str> {
match alignment {
Alignment::None => None,
Alignment::Left => Some("left"),
Alignment::Center => Some("center"),
Alignment::Right => Some("right"),
}
}
#[doc(hidden)]
pub fn read_picture(bytes: Vec<u8>, alt: &str) -> Option<Picture> {
use image::ImageFormat;
let reader = image::ImageReader::new(std::io::Cursor::new(&bytes))
.with_guessed_format()
.ok()?;
let (extension, content_type) = match reader.format()? {
ImageFormat::Png => ("png", "image/png"),
ImageFormat::Jpeg => ("jpeg", "image/jpeg"),
ImageFormat::Gif => ("gif", "image/gif"),
ImageFormat::Bmp => ("bmp", "image/bmp"),
ImageFormat::Tiff => ("tiff", "image/tiff"),
_ => return None,
};
let (width, height) = reader.into_dimensions().ok()?;
if width == 0 || height == 0 {
return None;
}
let mut cx = u64::from(width) * 9525;
let mut cy = u64::from(height) * 9525;
if cx > MAX_PICTURE_WIDTH {
cy = cy * MAX_PICTURE_WIDTH / cx;
cx = MAX_PICTURE_WIDTH;
}
Some(Picture {
bytes,
extension,
content_type,
width: cx,
height: cy.max(1),
alt: alt.to_string(),
})
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod tests {
use super::*;
#[test]
fn tight_amount_lists_need_a_constant_number_of_math_passes() {
let source = (5..2005)
.map(|n| format!("${n}"))
.collect::<Vec<_>>()
.join(",");
let (escaped, passes) = inline_math_passes(source, true);
assert!(
passes <= 3,
"2,000 amounts took {passes} full parses (limit 3)"
);
assert!(
!Parser::new_ext(&escaped, parser_options())
.any(|event| { matches!(event, Event::InlineMath(_) | Event::DisplayMath(_)) })
);
}
#[test]
fn a_comment_body_holding_a_date_keeps_its_author() {
assert_eq!(
named("Ana (2026-01-01T00:00:00Z): moved to (2026-02-01T00:00:00Z)"),
Some((
Some("Ana".to_string()),
"2026-01-01T00:00:00Z",
": moved to (2026-02-01T00:00:00Z)"
))
);
assert_eq!(
named("Ana (Legal) (2026-01-01T00:00:00Z): see (2026-02-01T00:00:00Z)"),
Some((
Some("Ana (Legal)".to_string()),
"2026-01-01T00:00:00Z",
": see (2026-02-01T00:00:00Z)"
))
);
}
#[test]
fn even_backslash_runs_move_off_the_pipes_they_shield() {
assert_eq!(unshield_pipes(r"|\\|\\\\|"), r"|\\ |\\\\ |");
assert_eq!(unshield_pipes(r"a\|b \\| c"), r"a\|b \\ | c");
assert_eq!(unshield_pipes(r"|\\\|x"), r"|\\\|x");
let spans = "|`a\\\\|b` x|$a\\\\|b$|<i t=\"a\\\\|b\"> y|";
assert_eq!(unshield_pipes(spans), spans);
}
#[test]
fn a_rows_pipes_unshield_only_where_a_table_matches_them() {
assert_eq!(
table_pipes("|\\\\|\\\\\\\\|\n|-|-|\n"),
"|\\\\ |\\\\\\\\ |\n|-|-|\n"
);
assert_eq!(table_pipes("|\\\\|x|y\n|-|-|\n"), "|\\\\|x|y\n|-|-|\n");
assert_eq!(table_pipes("\\\\|x\n"), "\\\\|x\n");
assert_eq!(table_pipes(" \\\\|x\n"), " \\\\|x\n");
assert_eq!(table_pipes("```\n\\\\|x\n```\n"), "```\n\\\\|x\n```\n");
assert_eq!(
table_pipes("---\ntext: |\n \\\\|x\n---\n"),
"---\ntext: |\n \\\\|x\n---\n"
);
}
#[test]
fn trailing_backslashes_only_move_when_a_table_opens() {
assert_eq!(
table_pipes("|\\\\| \\\n|---|---|\n"),
"|\\\\ | \\ \n|---|---|\n"
);
assert_eq!(table_pipes("|\\\n|---|\n"), "|\\ \n|---|\n");
assert_eq!(
table_pipes("|\\\\\\\n|---|\n"),
"|\\\\\\ \n|---|\n",
"a run of three backslashes is odd too"
);
assert_eq!(
table_pipes("|\\\r\n|---|\r\n"),
"|\\ \r\n|---|\r\n",
"a carriage return keeps its place after the space"
);
assert_eq!(table_pipes("|\\\\\n|---|\n"), "|\\\\\n|---|\n");
assert_eq!(table_pipes("|\\\n| a |\n"), "|\\\n| a |\n");
assert_eq!(
table_pipes("| a |\n|---|\n| x | y\\\n"),
"| a |\n|---|\n| x | y\\\n",
"a row inside a table keeps its bytes"
);
assert_eq!(table_pipes("```\n|\\\n```\n"), "```\n|\\\n```\n");
for source in [
"|\\\n|---|---|\n", " |\\\n |---|\n", "\t|\\\n\t|---|\n",
" \t|\\\n \t|---|\n",
"\u{a0}|\\\n|---|\n", "~~~\n|\\\n|---|\n~~~\n",
"---\ntext: |\n |\\\n |---|\n---\n", "|\\\n |---|\n", "|\\\n\t|---|\n",
"|\\\n\u{a0}|---|\n",
] {
assert_eq!(table_pipes(source), source);
}
}
#[test]
fn indented_backslash_headers_match_their_delimiter_columns() {
for indent in [" ", " ", " "] {
let source = format!("{indent}|\\\n{indent}|---|\n");
let expected = format!("{indent}|\\ \n{indent}|---|\n");
assert_eq!(table_pipes(&source), expected);
}
}
#[test]
fn dates_are_iso_8601_to_the_minute_or_finer() {
for date in [
"2026-01-02T03:04",
"2026-01-02T03:04:05",
"2026-01-02T03:04:05Z",
"2026-01-02T03:04:05.123Z",
"2026-01-02T03:04:05+01:00",
"2026-01-02T03:04-05:30",
"2024-02-29T23:59:59Z",
"2026-12-31T00:00+14:00",
] {
assert!(is_date(date), "{date}");
}
for text in [
"",
"2026-01-02",
"2026-1-02T03:04",
"26-01-02T03:04",
"2026-01-02T3:04",
"2026-01-02T03:04:5",
"2026-01-02T03:04:05.Z",
"2026-01-02T03:04:05+0100",
"2026-01-02T03:04:05+01:0x",
"2026-01-02T03:04:05:06",
"yesterday",
"2026-02-30T00:00:00Z",
"2025-02-29T00:00",
"2026-13-01T00:00Z",
"2026-00-01T00:00Z",
"2026-01-00T00:00Z",
"2026-01-02T24:00:00Z",
"2026-01-02T03:60Z",
"2026-01-02T03:04:60Z",
"2026-01-02T03:04+15:00",
"2026-99-99T99:99:99Z",
] {
assert!(!is_date(text), "{text}");
}
}
#[test]
fn a_revision_note_numbers_the_marks_of_its_changes() {
let tag = |ids: &[u32]| view_notes::Tag {
handle: "AC".into(),
date: None,
ids: ids.to_vec(),
};
assert_eq!(mark_ids(&[tag(&[1, 2])], 2), [vec![1], vec![2]]);
assert_eq!(mark_ids(&[tag(&[5, 6])], 1), [vec![5, 6]]);
assert_eq!(mark_ids(&[tag(&[1, 2, 3])], 2), [vec![1], vec![2, 3]]);
assert_eq!(mark_ids(&[tag(&[4])], 2), [vec![4], vec![]]);
assert_eq!(mark_ids(&[tag(&[1]), tag(&[2])], 2), [vec![1], vec![2]]);
assert!(mark_ids(&[], 2).is_empty());
assert!(mark_ids(&[tag(&[1])], 0).is_empty());
}
#[test]
fn names_and_attributions() {
assert_eq!(
named("Ana Lima (2026-01-02T03:04Z): hi"),
Some((Some("Ana Lima".to_string()), "2026-01-02T03:04Z", ": hi"))
);
assert_eq!(
named("(2026-01-02T03:04Z)"),
Some((None, "2026-01-02T03:04Z", ""))
);
for text in [
"Ana(2026-01-02T03:04Z)",
" (2026-01-02T03:04Z)",
"Ad)a (2026-01-02T03:04Z)",
"Ana (soon)",
"Ana 2026-01-02T03:04Z",
] {
assert_eq!(named(text), None, "{text}");
}
assert_eq!(
named("A (b) (2026-01-02T03:04Z)"),
Some((Some("A (b)".to_string()), "2026-01-02T03:04Z", ""))
);
assert_eq!(
named("A %28b%29 (2026-01-02T03:04Z)"),
Some((Some("A (b)".to_string()), "2026-01-02T03:04Z", ""))
);
assert_eq!(
attribution("Bo (2026-01-02T03:04:05Z)"),
Some((Some("Bo".to_string()), "2026-01-02T03:04:05Z"))
);
assert_eq!(attribution("Bo (2026-01-02T03:04:05Z): why"), None);
assert_eq!(attribution("Bo"), None);
}
#[test]
fn a_substitution_split_by_dropped_text_keeps_its_separator() {
assert_eq!(
loose_tokens(vec![Token::SubstituteStart, Token::SubstituteSeparator,]),
vec![Token::SubstituteStart, Token::SubstituteSeparator]
);
assert_eq!(
loose_tokens(vec![
Token::SubstituteStart,
Token::SubstituteSeparator,
Token::SubstituteEnd,
]),
vec![]
);
assert_eq!(
loose_tokens(vec![
Token::InsertEnd,
Token::SubstituteStart,
Token::SubstituteSeparator,
Token::SubstituteEnd,
]),
vec![Token::InsertEnd]
);
}
#[test]
fn a_paragraph_mark_whole_inside_dropped_text_drops_with_it() {
assert_eq!(
loose_tokens(vec![Token::ParagraphInsertion, Token::AttributionEnd]),
vec![]
);
assert_eq!(
loose_tokens(vec![Token::ParagraphInsertion]),
vec![Token::ParagraphInsertion]
);
assert_eq!(
loose_tokens(vec![
Token::AttributionStart,
Token::ParagraphInsertion,
Token::AttributionEnd
]),
vec![Token::AttributionStart]
);
assert_eq!(
loose_tokens(vec![
Token::ParagraphInsertion,
Token::AttributionStart,
Token::AttributionEnd
]),
vec![Token::ParagraphInsertion]
);
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod markdown_authored_boundary_tests {
use super::*;
#[test]
fn malformed_iso_components_cannot_become_revision_attributions() {
let invalid = [
"2026-10T12:34",
"2026-10-09-01T12:34",
"xxxx-10-09T12:34",
"2026-xx-09T12:34",
"2026-10-xxT12:34",
"2026-10-09T12:34:ab",
"2026-10-09T12:34:01.ab",
"2026-10-09T12:34+01x30",
"2026-10-09T12:34+ab:30",
"2026-10-09T12:34+01:ab",
"2026-10-09T12:34+",
"2026-10-09T12:34:01:02",
"2026-10-09T12:34:01.",
"2026-10-09Txx:34",
"2026-10-09T12:xx",
];
for date in invalid {
assert!(!is_date(date), "{date}");
assert_eq!(
named(&format!("Ada ({date}): owned comment")),
None,
"{date}"
);
assert_eq!(attribution(&format!("Ada ({date})")), None, "{date}");
}
for date in [
"2026-10-09T12:34",
"2026-10-09T12:34:00.5-03:30",
"2026-10-09T12:34+00:00",
] {
assert!(is_date(date), "{date}");
let input = format!("Ada ({date}): owned comment");
assert_eq!(
named(&input),
Some((Some("Ada".to_string()), date, ": owned comment"))
);
assert_eq!(attribution(&input), None);
}
let date = "2026-10-09T12:34Z";
for author in ["Ad)a ", "Ada", " ", "\t"] {
assert_eq!(named(&format!("{author}({date})")), None, "{author:?}");
}
}
#[test]
fn front_matter_quote_variants_preserve_decoded_authored_metadata() {
for (title, author) in [
("'Agreement'", "'Ada'"),
("\"Agreement\"", "\"Ada\""),
("Agreement", "Ada"),
] {
let source = format!(
"---\ntitle: {title}\nauthor: {author}\nignored: extra\nempty: ''\n---\n\nBody"
);
let document = read(&source, &DocxOptions::default());
assert_eq!(document.title.as_deref(), Some("Agreement"));
assert_eq!(document.author.as_deref(), Some("Ada"));
assert_eq!(
document.body,
vec![
Item::Paragraph(Paragraph::default()),
Item::Run(Run {
content: Content::Text("Body".to_string()),
format: RunFormat::default(),
change: None,
scope: None
}),
Item::ParagraphEnd,
]
);
assert!(document.comments.is_empty());
assert!(document.warnings.is_empty());
}
}
#[test]
fn comment_links_and_non_attribution_suffixes_keep_the_complete_comment() {
let date = "2026-10-09T12:34Z";
for (source, expected, by) in [
(
"Body{>>[owned](https://example.invalid) tail<<}".to_string(),
"owned tail".to_string(),
None,
),
(
format!("Body{{>>Ada ({date}) suffix<<}}"),
format!("Ada ({date}) suffix"),
None,
),
(
format!("Body{{>>Ada ({date}): owned text<<}}"),
"owned text".to_string(),
Some(("Ada".to_string(), date.to_string())),
),
(
"Body{>>one<br>two<<}".to_string(),
"one\ntwo".to_string(),
None,
),
] {
let document = read(&source, &DocxOptions::default());
assert_eq!(document.comments.len(), 1, "{source}");
let comment = &document.comments[0];
assert_eq!(comment.id, 0);
assert_eq!(comment.paragraphs.join("\n"), expected, "{source}");
assert_eq!(comment.by, by, "{source}");
assert_eq!(
document
.body
.iter()
.filter_map(|item| match item {
Item::Run(run) => Some(&run.content),
_ => None,
})
.collect::<Vec<_>>(),
vec![&Content::Text("Body".to_string())]
);
assert_eq!(
document
.body
.iter()
.filter(|item| matches!(item, Item::CommentReference(0)))
.count(),
1
);
assert_eq!(
document
.body
.iter()
.filter(|item| matches!(item, Item::LinkStart(..) | Item::LinkEnd))
.count(),
0
);
assert!(document.attributions.is_empty());
assert!(document.warnings.is_empty());
}
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod memory_picture_import_contract_tests {
use super::*;
fn encoded(format: image::ImageFormat, width: u32, height: u32) -> Vec<u8> {
let image = image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(
width,
height,
image::Rgb([31, 97, 163]),
));
let mut out = std::io::Cursor::new(Vec::new());
image.write_to(&mut out, format).unwrap();
out.into_inner()
}
#[test]
fn memory_picture_formats_keep_exact_payload_alt_and_capped_aspect_ratio() {
for (format, extension, mime) in [
(image::ImageFormat::Png, "png", "image/png"),
(image::ImageFormat::Jpeg, "jpeg", "image/jpeg"),
(image::ImageFormat::Gif, "gif", "image/gif"),
(image::ImageFormat::Bmp, "bmp", "image/bmp"),
(image::ImageFormat::Tiff, "tiff", "image/tiff"),
] {
for (width, height, cx, cy) in [
(1, 2, 9525, 19050),
(624, 1, 5_943_600, 9525),
(625, 2, 5_943_600, 19019),
] {
let bytes = encoded(format, width, height);
let got = read_picture(bytes.clone(), "owned Ω alt").unwrap();
assert_eq!(got.bytes, bytes);
assert_eq!(got.extension, extension);
assert_eq!(got.content_type, mime);
assert_eq!((got.width, got.height), (cx, cy));
assert_eq!(got.alt, "owned Ω alt");
}
}
}
#[test]
fn rejected_memory_images_preserve_alt_text_and_report_only_requested_load_failures() {
for bytes in [
Vec::new(),
b"not an image".to_vec(),
b"\x89PNG\r\n\x1a\n".to_vec(),
b"RIFF\x04\0\0\0WEBP".to_vec(),
] {
assert!(read_picture(bytes.clone(), "owned").is_none());
let load = |url: &str| {
assert_eq!(url, "owned.png");
Some(bytes.clone())
};
let options = DocxOptions {
images: Some(&load),
..DocxOptions::default()
};
let doc = read("before  after", &options);
assert!(doc.pictures.is_empty());
assert_eq!(
doc.warnings,
["image 'owned.png' was written as its alt text"]
);
let text: String = doc
.body
.iter()
.filter_map(|item| match item {
Item::Run(Run {
content: Content::Text(text),
..
}) => Some(text.as_str()),
_ => None,
})
.collect();
assert_eq!(text, "before owned Ω after");
}
let no_load = read("", &DocxOptions::default());
assert!(no_load.warnings.is_empty());
assert!(no_load.pictures.is_empty());
assert!(no_load.body.iter().any(|item| matches!(item, Item::Run(Run { content: Content::Text(text), .. }) if text == "owned Ω")));
let load = |_: &str| None;
let missing = read(
"",
&DocxOptions {
images: Some(&load),
..DocxOptions::default()
},
);
assert_eq!(
missing.warnings,
["image 'owned.png' was written as its alt text"]
);
assert!(missing.pictures.is_empty());
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod html_tag_tests {
use super::*;
#[test]
fn a_paragraph_break_is_br_by_name_and_not_self_closing() {
for br in ["<br>", "<BR>", "<br class=\"x\">", "< br >"] {
assert!(is_paragraph_break(br), "{br}");
}
for not in ["<br/>", "<BR />", "</br>", "<bra>", "<br-x>", "<b>"] {
assert!(!is_paragraph_break(not), "{not}");
}
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod helper_branch_tests {
use super::*;
#[test]
fn front_matter_closes_on_dots_and_crlf_and_needs_a_closer() {
assert_eq!(
split_front_matter("---\r\ntitle: x\r\n...\r\nbody"),
Some(("title: x\r\n", "body"))
);
assert_eq!(split_front_matter("---\nunclosed: yes\n"), None);
assert_eq!(split_front_matter("no front matter"), None);
}
#[test]
fn page_commands_skip_front_matter_and_fences_and_end_without_a_newline() {
assert_eq!(
page_commands("---\na: \\newpage\n...\n\\newpage"),
format!("---\na: \\newpage\n...\n{PAGE_BREAK_LINE}\n")
);
assert_eq!(
page_commands("~~~\n\\pagebreak\n~~~ \n\\clearpage\r\n"),
format!("~~~\n\\pagebreak\n~~~ \n{PAGE_BREAK_LINE}\r\n")
);
assert_eq!(page_commands(" \\newpage\n"), " \\newpage\n");
assert_eq!(
page_commands("```\n``` x\n\\newpage\n"),
"```\n``` x\n\\newpage\n"
);
}
#[test]
fn table_pipes_leave_front_matter_closed_by_dots() {
let source = "---\nrow: |\\\\|x\n...\n|\\\\|y|\n|-|-|\n";
assert_eq!(
table_pipes(source),
"---\nrow: |\\\\|x\n...\n|\\\\ |y|\n|-|-|\n"
);
assert_eq!(table_pipes("\t|\\\\|x\n|-|\n"), "\t|\\\\|x\n|-|\n");
assert_eq!(table_pipes("|\\\\|x\n |-|-|\n"), "|\\\\|x\n |-|-|\n");
}
#[test]
fn unshield_pipes_treat_escaped_openers_as_text() {
assert_eq!(unshield_pipes(r"\`a\\|b`"), r"\`a\\ |b`");
assert_eq!(unshield_pipes(r"\$a\\|b$"), r"\$a\\ |b$");
assert_eq!(unshield_pipes(r"\<b>\\|"), r"\<b>\\ |");
assert_eq!(unshield_pipes(r"$$a$\$\\|b$$|"), r"$$a$\$\\|b$$|");
assert_eq!(unshield_pipes(r"`a\\|"), r"`a\\ |");
assert_eq!(unshield_pipes(r"$a\\|"), r"$a\\ |");
assert_eq!(unshield_pipes(r"<1\\|"), r"<1\\ |");
assert_eq!(unshield_pipes(r"<a\\|"), r"<a\\ |");
assert_eq!(unshield_pipes("é\\\\|"), "é\\\\ |");
}
#[test]
fn delimiter_rows_and_row_columns_follow_gfm() {
assert!(delimiter_row("|:-:|---:|"));
assert!(delimiter_row("--- | ---"));
assert!(!delimiter_row("|:|-|"));
assert!(!delimiter_row("||"));
assert!(!delimiter_row("|a-|"));
assert_eq!(row_columns("a|b"), 2);
assert_eq!(row_columns("a|b|"), 2);
assert_eq!(row_columns("|a|b"), 2);
assert_eq!(row_columns(r"|a\|b|"), 1);
assert_eq!(row_columns(r"|a\\|b|"), 2);
assert_eq!(row_columns("plain"), 1);
}
#[test]
fn item_columns_measure_tabs_numbers_and_wide_gaps() {
assert_eq!(item_columns("- x", 0), (0, 2));
assert_eq!(item_columns("\t- x", 0), (4, 6));
assert_eq!(item_columns("1) x", 0), (0, 3));
assert_eq!(item_columns("12. x", 0), (0, 4));
assert_eq!(item_columns("7 x", 0), (0, 2));
assert_eq!(item_columns("- x", 0), (0, 2));
assert_eq!(item_columns("-\tx", 0), (0, 4));
assert_eq!(item_columns("-", 0), (0, 2));
assert_eq!(item_columns("- ", 0), (0, 2));
assert_eq!(item_columns("- - x", 2), (2, 4));
assert_eq!(item_columns("1. 2. x", 3), (3, 6));
assert_eq!(item_columns("ab", 0), (2, 2));
assert_eq!(item_columns("a\n- b", 2), (0, 2));
}
#[test]
fn html_attributes_read_quoted_bare_and_skip_lookalikes() {
assert_eq!(
html_attribute("<a xhref=\"no\" href=\"yes\">", "href"),
Some("yes".to_string())
);
assert_eq!(
html_attribute("<a href title=x>", "href"),
None,
"an attribute with no value"
);
assert_eq!(
html_attribute("<a href title=x>", "title"),
Some("x".to_string())
);
assert_eq!(
html_attribute("<a href=u&v class=c>", "href"),
Some("u&v".to_string())
);
assert_eq!(
html_attribute("<a href='q'>", "href"),
Some("q".to_string())
);
assert_eq!(
html_attribute("<a href=\"open", "href"),
Some("open".into())
);
assert_eq!(html_attribute("<a>", "href"), None);
}
#[test]
fn symbol_tags_and_comment_blocks_are_recognised_exactly() {
assert!(is_symbol_tag("<sym font=\"Wingdings\" char=\"F0FC\"/>"));
assert!(!is_symbol_tag("<sym>"));
assert!(!is_symbol_tag("x<sym/>"));
assert!(!is_symbol_tag("<b/>"));
assert!(!is_symbol_tag("<sym/><sym/>"));
assert!(!is_symbol_tag("</sym/>"));
assert!(comments_only("<!-- p1 -->\n\n <!-- p2 -->\n"));
assert!(!comments_only("<!-- p1 -->\n<div>"));
assert!(!comments_only("<!-- open"));
}
#[test]
fn html_block_text_drops_tags_comments_scripts_and_styles() {
let (first, paragraphs) = html_block_text(
"<!-- c --><div>One & <b>two</b></div><p>three</p>\
<script>bad()</script><STYLE>x{}</style><style/>four</br>",
);
assert_eq!(first.as_deref(), Some("div"));
assert_eq!(paragraphs, ["One & two", "three", "four"]);
assert_eq!(html_block_text("a < b").1, ["a < b"]);
assert_eq!(html_block_text("<>x<1>y").1, ["xy"]);
assert_eq!(html_block_text("a<!-- open").1, ["a"]);
assert_eq!(
html_block_text("<script>never closed").1,
Vec::<String>::new()
);
assert_eq!(html_block_text("</script>after").1, ["after"]);
assert_eq!(html_block_text("").0, None);
}
#[test]
fn html_tags_parse_names_and_reject_non_tags() {
let tag = html_tag("< / Code-X >").expect("a tag");
assert_eq!(
(tag.name.as_str(), tag.closing, tag.empty),
("code-x", true, false)
);
assert!(html_tag("<br/>").is_some_and(|t| t.empty));
assert!(html_tag("<!-- c -->").is_none());
assert!(html_tag("<?pi?>").is_none());
assert!(html_tag("<1a>").is_none());
assert!(html_tag("<b").is_none());
assert!(html_tag("b>").is_none());
assert!(html_is_page_break("<br type = 'PAGE' />"));
assert!(!html_is_page_break("<br>"));
}
#[test]
fn highlight_classes_name_word_colours_only() {
assert_eq!(hl_color_class("HL-Cyan"), Some("cyan"));
assert_eq!(hl_color_class("hl-darkGray"), Some("darkGray"));
assert_eq!(hl_color_class("hl-none"), None);
assert_eq!(hl_color_class("hl-teal"), None);
assert_eq!(hl_color_class("hx-red"), None);
assert_eq!(hl_color_class("h"), None);
}
#[test]
fn move_clauses_peel_and_decode_their_names() {
assert_eq!(decode_move_name("a%20b%25c"), "a b%c");
assert_eq!(decode_move_name("100%"), "100%");
assert_eq!(decode_move_name("x%41y"), "x%41y");
assert_eq!(decode_move_name("%2"), "%2");
assert_eq!(
peel_move_part(" r1 @A move m%201 "),
("r1 @A".to_string(), Some("m 1".to_string()))
);
assert_eq!(
peel_move_part("r1 @A move"),
("r1 @A".to_string(), Some(String::new()))
);
assert_eq!(
peel_move_part("r1 @A move two words"),
("r1 @A move two words".to_string(), None)
);
let (note, names) = peeled_note("r1 @A re r0 @B");
assert_eq!(note, "r1 @A re r0 @B");
assert_eq!(names, [None, None]);
let (note, names) = peeled_note("r1 @A move m1");
assert_eq!(note, "r1 @A");
assert_eq!(names, [Some("m1".to_string())]);
let (note, names) = peeled_note("just words move m1");
assert_eq!(note, "just words move m1");
assert_eq!(names, [None]);
}
#[test]
fn scholar_fills_only_what_the_front_matter_leaves_out() {
let out = scholar(
"---\nstyles:\n Body: Arial 11pt # mine\n \"#\": Heading1, bold\n odd\nfooters:\n default: {id: footer1, text: \"{PAGE}\"}\n---\n\nText",
false,
);
assert!(!out.contains("Latin Modern Roman 10pt"), "{out}");
assert!(!out.contains("Heading1, Latin Modern"), "{out}");
assert!(out.contains("Heading2, Latin Modern"), "{out}");
assert_eq!(out.matches("footers:").count(), 1, "{out}");
let out = scholar(
"---\nstyles:\n table: TableGrid\nheaders:\n default: {id: header1, text: Firm}\n---\nText",
false,
);
assert!(out.contains(" Normal: Latin Modern Roman 10pt"), "{out}");
assert!(!out.contains("first: none"), "{out}");
assert!(out.contains("default: {id: footer1, text: \"{PAGE}\", center}"));
let out = scholar(
"---\nstyles:\n Body: x\n \"#\": a\n \"##\": b\n \"###\": c\n---\nText",
true,
);
assert!(!out.contains("Latin Modern"), "{out}");
assert!(!out.contains("footers:"), "{out}");
let out = scholar("Text", false);
assert!(out.starts_with("---\nstyles:\n Normal:"), "{out}");
assert!(out.contains(" first: none"), "{out}");
}
#[test]
fn distribute_marks_quotes_headings_rows_and_refuses_bare_markers() {
assert_eq!(
distribute("> a\n> b\nc", "{++", "++}").as_deref(),
Some("> {++a\n> b++}\n{++c++}")
);
assert_eq!(
distribute("# H\nnext", "{--", "--}").as_deref(),
Some("# {--H--}\n{--next--}")
);
assert_eq!(distribute("#", "{++", "++}"), None);
assert_eq!(distribute("- ", "{++", "++}"), None);
assert_eq!(
distribute("\n- a", "{++", "++}").as_deref(),
Some("\n- {++a++}")
);
assert!(blocky("```\ncode\n```"));
assert!(blocky("| a | b |"));
assert!(!blocky("plain text"));
assert_eq!(substitution_blocks("a", "b", true), None);
assert_eq!(substitution_blocks("- a", "- b", false), None);
assert_eq!(
substitution_blocks("- a", "- b", true).as_deref(),
Some("- {--a--}\n- {++b++}")
);
assert_eq!(substitution_blocks("#", "- b", true), None);
}
#[test]
fn text_box_markers_refuse_duplicates_and_overlaps() {
let (boxes, error) =
text_box_sources("<!-- text-box d1.0 -->\n\nOne<br>two\n\n<!-- /text-box -->\n");
assert_eq!(boxes.get("d1.0").map(String::as_str), Some("One\ntwo"));
assert_eq!(error, None);
let (_, error) = text_box_sources(
"<!-- text-box d1.0 -->\n\n<!-- text-box d2.0 -->\n\nx\n\n<!-- /text-box -->\n",
);
assert_eq!(
error.as_deref(),
Some("text-box d2.0: duplicate or overlapping marker region")
);
let (_, error) = text_box_sources(
"<!-- text-box d1.0 -->\n\n<!-- /text-box -->\n\n<!-- text-box d1.0 -->\n\n<!-- /text-box -->\n",
);
assert!(error.is_some());
let (boxes, error) = text_box_sources("<!-- /text-box -->\n");
assert!(boxes.is_empty() && error.is_none());
}
#[test]
fn style_change_tags_name_their_property() {
assert!(matches!(
style_change_tag("pPr r1 @A"),
(StyleChangeKind::Paragraph, "r1 @A", false)
));
assert!(matches!(
style_change_tag("other r1"),
(StyleChangeKind::Other, "r1", false)
));
assert!(matches!(
style_change_tag("r1"),
(StyleChangeKind::Run, "r1", true)
));
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod inline_branch_tests {
use super::*;
const PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";
fn part(markdown: &str, critic: bool, part: &str) -> String {
let options = DocxOptions {
critic,
..DocxOptions::default()
};
let written = markdown_to_docx(markdown, &options).expect("writes");
crate::opc::PartFs::open(&written.docx)
.expect("opens")
.part_string(part)
.unwrap_or_default()
}
fn body(markdown: &str) -> String {
part(markdown, true, "/word/document.xml")
}
#[test]
fn math_where_no_equation_goes_stays_latex_text() {
let image = format!("");
for critic in [true, false] {
let xml = part(&image, critic, "/word/document.xml");
assert!(
xml.contains("descr=\"see $x^2$ and $$y$$\""),
"{critic}: {xml}"
);
}
let comments = part("Text{>>has $x$ and $$y$$<<}", true, "/word/comments.xml");
assert!(comments.contains("has $x$ and $$y$$"), "{comments}");
assert!(!body("Text{>>has $x$<<}").contains("<m:oMath"));
}
#[test]
fn inline_html_writes_symbols_links_bookmarks_and_breaks() {
let xml = body(
"A<sym font=\"Symbol\" char=\"F0B7\"/>B<sym font=\"\" char=\"F0B7\"/>C<sym font=\"Symbol\" char=\"F0B7\">D",
);
assert_eq!(xml.matches("<w:sym ").count(), 1, "{xml}");
assert!(xml.contains("w:font=\"Symbol\" w:char=\"F0B7\""), "{xml}");
let xml = body(
"Go <a href=\"https://x.test\" title=\"tip\">there</a> or <a name=\"spot\">here</a><a id=\"\">x</a>.",
);
assert!(xml.contains("<w:hyperlink"), "{xml}");
assert!(xml.contains("w:name=\"spot\""), "{xml}");
assert_eq!(xml.matches("<w:bookmarkStart").count(), 1, "{xml}");
let xml = body("one<br>two</br>three<b/>four");
assert_eq!(xml.matches("<w:br/>").count(), 1, "{xml}");
assert!(!xml.contains("<w:b/>"), "{xml}");
let xml = body("Mail <a@b.co> now");
assert!(xml.contains("<w:hyperlink"), "{xml}");
assert!(xml.contains(">a@b.co</w:t>"), "{xml}");
let xml = body("<div>\nblock text\n</div>\n\nAfter");
assert!(xml.contains("After"), "{xml}");
let xml = body("Note{>>a <b>bold</b> word<<} after");
assert!(xml.contains(">after<") || xml.contains(" after<"), "{xml}");
assert!(!xml.contains("<w:b/>"), "{xml}");
}
#[test]
fn tables_and_lists_keep_their_cells_and_items() {
let xml = body(
"| a | b | c |\n|:--|:-:|--:|\n| 1 | | 3 |\n| x |\n\n- one\n- two\n - nested\n\n1. first\n2. second\n",
);
assert_eq!(
xml.matches("<w:tr>").count() + xml.matches("<w:tr ").count(),
3,
"{xml}"
);
assert!(
xml.contains("w:val=\"center\"") && xml.contains("w:val=\"right\""),
"{xml}"
);
for text in ["nested", "first", "second"] {
assert!(xml.contains(text), "{text}: {xml}");
}
}
}