Skip to main content

jubarte_edit/markdown/
patch.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! A Markdown edit of a Word document, applied to the document itself.
6//!
7//! The Markdown is read as the document's text after an edit, however it
8//! was made (pandoc, `jubarte text`, a converter, an agent). Its blocks
9//! are aligned with the body's paragraphs by their text, and only what
10//! differs is edited, through an [edit plan](crate::edit): a paragraph
11//! whose text changed is rewritten word by word, so its runs,
12//! formatting, fields and properties stay; a block the document lacks
13//! becomes a paragraph next to its neighbours, taking the properties of
14//! a neighbour of its kind; a paragraph the Markdown lacks is deleted.
15//! Empty paragraphs, which Markdown cannot hold, are left alone, and
16//! typed numbering (`1.`, `(a)`) that the Markdown writes as a list
17//! marker is kept.
18//!
19//! Backs `jubarte edit FILE EDITIONS.md`, the `PATCH.md` edit-plan
20//! companion path (a Markdown sketch of the same edits), and the
21//! Python / WASM [`apply_markdown`] binding.
22
23use std::collections::HashSet;
24
25use pulldown_cmark::{Event, HeadingLevel, Options, Parser, Tag, TagEnd};
26use similar::{Algorithm, DiffTag, capture_diff_slices};
27
28use super::MarkdownError;
29use super::diff::similarity;
30use crate::edit::{
31    EditPlan, ExistingRevisions, Operation, OperationKind, RunSpec, Selector, Side, apply_plan,
32};
33
34/// Paragraphs that share less than this share of their words pair only when
35/// nothing better is left between two pairs.
36const PAIR_SIMILARITY: f64 = 0.3;
37
38/// Pairing compares every paragraph of a changed stretch with every block
39/// of it; above this many comparisons they pair by position.
40const MAX_PAIRINGS: usize = 2_500;
41
42/// A Word document the Markdown edits landed on.
43///
44/// Returned by [`apply_markdown`]; writes a clean `.docx` (no tracked
45/// changes) where the Markdown rewrote, inserted or deleted body
46/// paragraphs, with anything the document could not take reported in
47/// [`Self::warnings`].
48#[derive(Clone, Debug, PartialEq, Eq)]
49pub struct Patched {
50    /// The edited `.docx`, without tracked changes.
51    pub docx: Vec<u8>,
52    /// What the Markdown changed that the document could not take: a
53    /// footnote whose text is on the Markdown side but not applied, a
54    /// table cell that would have needed row and column work the engine
55    /// does not attempt, a paragraph the engine could not edit for the
56    /// reason the first failure gave.
57    pub warnings: Vec<String>,
58}
59
60/// The kind of a block or paragraph, for pairing and for the properties a
61/// new paragraph copies.
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63enum Kind {
64    Heading(u8),
65    List,
66    Cell,
67    Plain,
68}
69
70/// A Markdown block: its kind, its plain text and its runs.
71#[derive(Clone, Debug)]
72struct Block {
73    kind: Kind,
74    runs: Vec<RunSpec>,
75}
76
77impl Block {
78    fn text(&self) -> String {
79        self.runs.iter().map(|r| r.text.as_str()).collect()
80    }
81}
82
83/// A body paragraph: its index in the body, text and kind.
84#[derive(Clone, Debug)]
85struct Paragraph {
86    index: usize,
87    text: String,
88    kind: Kind,
89}
90
91/// Edits `docx` so its body reads as `markdown`, keeping the
92/// paragraphs' own runs, formatting, fields and properties, and
93/// reporting what the document could not take in
94/// [`Patched::warnings`]. A document with tracked changes is read with
95/// them accepted; the result is a clean `.docx`.
96///
97/// Backs `jubarte edit FILE EDITIONS.md` and the Python / WASM
98/// `apply_markdown` binding.
99///
100/// # Errors
101///
102/// [`MarkdownError::Package`] when:
103/// - the source fails to admit, list its tracked changes, or list its
104///   body paragraphs (covered by `InspectError`);
105/// - the edit-plan engine refuses an edit the engine cannot represent
106///   after four retries at falling back to whole-paragraph replacements
107///   and dropping the failing edits.
108///
109/// Footnote text, which the body-only editor does not apply, is a warning
110/// in [`Patched::warnings`], not an error.
111///
112/// ```
113/// use jubarte_edit::markdown::{DocxOptions, apply_markdown, markdown_to_docx};
114///
115/// let original = markdown_to_docx("Pay in 30 days.\n\nSigned.\n", &DocxOptions::default())
116///     .unwrap()
117///     .docx;
118/// let edited = apply_markdown(&original, "Pay in 45 days.\n\nSigned.\n").unwrap();
119/// assert!(edited.warnings.is_empty());
120/// ```
121pub fn apply_markdown(docx: &[u8], markdown: &str) -> Result<Patched, MarkdownError> {
122    apply_markdown_exact(docx, markdown, false)
123}
124
125/// Edits `docx` so its body reads as `markdown`, and returns an error
126/// with no document when any edit cannot be applied as written.
127/// A refused rewrite stays refused: it is not replaced by a whole
128/// paragraph, and it is not left out of an otherwise applied result.
129///
130/// Footnote text is outside the body-only editor in both paths, so it
131/// stays the warning [`apply_markdown`] gives, not a refusal.
132///
133/// # Errors
134///
135/// [`MarkdownError::Package`] when the source fails to admit or list its
136/// paragraphs, when the edit-plan engine refuses any edit, or when the
137/// Markdown adds a table row or cell, which the editor cannot add.
138pub fn apply_markdown_strict(docx: &[u8], markdown: &str) -> Result<Patched, MarkdownError> {
139    apply_markdown_exact(docx, markdown, true)
140}
141
142fn apply_markdown_exact(
143    docx: &[u8],
144    markdown: &str,
145    strict: bool,
146) -> Result<Patched, MarkdownError> {
147    let invalid = |e: &dyn std::fmt::Display| MarkdownError::Package(e.to_string());
148    let summary = crate::inspect::summary(docx).map_err(|e| invalid(&e))?;
149    // A plan that accepts existing revisions addresses the accepted text.
150    let base = if summary.revisions > 0 {
151        crate::document_comparer::accept_revisions(docx).map_err(|e| invalid(&e))?
152    } else {
153        docx.to_vec()
154    };
155    let paragraphs: Vec<Paragraph> = crate::inspect::paragraphs(&base)
156        .map_err(|e| invalid(&e))?
157        .into_iter()
158        .filter(|p| !p.text.trim().is_empty())
159        .map(|p| Paragraph {
160            index: p.index,
161            kind: match p.style.as_deref().and_then(heading_level) {
162                Some(level) => Kind::Heading(level),
163                None if p.in_table => Kind::Cell,
164                None if p.numbered => Kind::List,
165                None => Kind::Plain,
166            },
167            text: p.text,
168        })
169        .collect();
170    let (blocks, notes) = blocks(markdown);
171    let mut warnings = Vec::new();
172    if notes {
173        warnings.push("footnote text is not applied: only the body is edited".to_string());
174    }
175    let edits = align(&paragraphs, &blocks);
176    let styles = paragraph_styles(&base);
177    for edit in &edits {
178        if let Edit::Insert(b, _) = edit
179            && blocks[*b].kind == Kind::Cell
180        {
181            let left_out = format!(
182                "table cell {:?} not applied: rows and columns are not added",
183                blocks[*b].text()
184            );
185            // A strict patch leaves nothing out: the row is the refusal.
186            if strict {
187                return Err(MarkdownError::Package(left_out));
188            }
189            warnings.push(left_out);
190        }
191    }
192
193    // Rewrites the engine refuses (text inside a link or a field) become
194    // whole-paragraph replacements, and what still fails is left out.
195    // The strict path does neither: the first refusal is the result.
196    let mut whole: HashSet<usize> = HashSet::new();
197    let mut dropped: HashSet<usize> = HashSet::new();
198    let attempts = if strict { 1 } else { 4 };
199    for _ in 0..attempts {
200        let operations = operations(&paragraphs, &blocks, &edits, &styles, &whole, &dropped);
201        if operations.is_empty() {
202            return Ok(Patched {
203                docx: base,
204                warnings,
205            });
206        }
207        let plan = EditPlan {
208            schema_version: crate::inspect::SCHEMA_VERSION,
209            source_sha256: None,
210            author: "jubarte".to_string(),
211            date: None,
212            initials: None,
213            removed_anchor_comments: Default::default(),
214            existing_revisions: ExistingRevisions::Accept,
215            resolve_revisions: None,
216            operations,
217            update_fields: false,
218            rewrite_others_comments: false,
219            others: crate::edit::Others::Allow,
220        };
221        match apply_plan(docx, &plan) {
222            Ok(result) => {
223                return Ok(Patched {
224                    docx: result.clean,
225                    warnings,
226                });
227            }
228            Err(error) => {
229                if strict {
230                    return Err(MarkdownError::Package(error.to_string()));
231                }
232                // Each failed edit once, with the first reason given.
233                let failed: std::collections::BTreeMap<usize, String> = error
234                    .outcomes
235                    .iter()
236                    .filter(|o| o.status == "failed")
237                    .chain(
238                        // A conflict names its operation but leaves it "ok".
239                        error
240                            .operation
241                            .iter()
242                            .filter_map(|id| error.outcomes.iter().find(|o| &o.id == id)),
243                    )
244                    .filter_map(|o| {
245                        let entry = o.id.split(':').nth(1)?.parse::<usize>().ok()?;
246                        let why = o.message.clone().unwrap_or_else(|| error.message.clone());
247                        Some((entry, why))
248                    })
249                    .rev()
250                    .collect();
251                if failed.is_empty() {
252                    return Err(MarkdownError::Package(error.to_string()));
253                }
254                for (entry, why) in failed {
255                    let rewrite = matches!(edits[entry], Edit::Pair(..));
256                    if rewrite && whole.insert(entry) {
257                        continue;
258                    }
259                    if dropped.insert(entry) {
260                        warnings.push(format!(
261                            "{} not applied: {why}",
262                            describe(&edits[entry], &paragraphs, &blocks)
263                        ));
264                    }
265                }
266            }
267        }
268    }
269    Err(MarkdownError::Package(
270        "the Markdown's changes could not be applied".to_string(),
271    ))
272}
273
274/// The paragraph styles a document defines, by lowercase name.
275fn paragraph_styles(docx: &[u8]) -> HashSet<String> {
276    let Ok(package) = crate::opc::PartFs::open(docx) else {
277        return HashSet::new();
278    };
279    let Some(xml) = package
280        .main_document_part()
281        .and_then(|main| {
282            let rels = package.read_rels_for(&main)?;
283            let rel = rels
284                .items
285                .iter()
286                .find(|r| r.rel_type.ends_with("/styles"))?;
287            Some(package.resolve_rel_target(&main, &rel.target))
288        })
289        .and_then(|part| package.part_string(&part))
290    else {
291        return HashSet::new();
292    };
293    let mut dom = crate::xmllinq::Dom::new();
294    let document = dom.parse_xdocument(&xml);
295    let Some(root) = dom.root(document) else {
296        return HashSet::new();
297    };
298    use crate::namespaces::W;
299    dom.elements(root, Some(&W::name("style")))
300        .into_iter()
301        // No `w:type` is a paragraph style (ECMA-376 `w:style`).
302        .filter(|&style| {
303            dom.attribute(style, &W::type_())
304                .is_none_or(|t| t == "paragraph")
305        })
306        .filter_map(|style| {
307            let name = dom.element(style, &W::name("name"))?;
308            Some(dom.attribute(name, &W::val())?.to_lowercase())
309        })
310        .collect()
311}
312
313/// One step of the alignment of paragraphs (by position in `paragraphs`)
314/// and blocks (by position in `blocks`).
315#[derive(Clone, Copy, Debug, PartialEq, Eq)]
316enum Edit {
317    /// A paragraph and the block it became; rewritten when they differ.
318    Pair(usize, usize),
319    /// A block the document lacks, inserted after paragraph `after` (or
320    /// before the first when `None`).
321    Insert(usize, Option<usize>),
322    /// A paragraph the Markdown lacks.
323    Delete(usize),
324}
325
326fn describe(edit: &Edit, paragraphs: &[Paragraph], blocks: &[Block]) -> String {
327    let excerpt = |text: &str| {
328        let short: String = text.chars().take(40).collect();
329        if short.len() < text.len() {
330            format!("\"{short}…\"")
331        } else {
332            format!("\"{short}\"")
333        }
334    };
335    match *edit {
336        Edit::Pair(p, b) => format!(
337            "rewriting paragraph {} as {}",
338            paragraphs[p].index,
339            excerpt(&blocks[b].text())
340        ),
341        Edit::Insert(b, _) => format!("inserting {}", excerpt(&blocks[b].text())),
342        Edit::Delete(p) => format!(
343            "deleting paragraph {} {}",
344            paragraphs[p].index,
345            excerpt(&paragraphs[p].text)
346        ),
347    }
348}
349
350/// Text compared for alignment: whitespace collapsed, symbols and leading
351/// typed numbering left out.
352fn key(text: &str) -> String {
353    let spaced = text.replace('\u{FFFC}', " ");
354    let collapsed = crate::util::collapse_whitespace(&spaced);
355    collapsed[enumerator_len(&collapsed)..].to_string()
356}
357
358/// The length of typed numbering at the start of `text` with the whitespace
359/// after it: `1.`, `1.2`, `(a)`, `b)`, `iv.`, `A.`. Zero when there is none.
360fn enumerator_len(text: &str) -> usize {
361    let bytes = text.as_bytes();
362    let mut at = 0;
363    let open = bytes.first() == Some(&b'(');
364    if open {
365        at += 1;
366    }
367    let body_start = at;
368    let digits = |from: usize| {
369        bytes[from..]
370            .iter()
371            .take_while(|b| b.is_ascii_digit())
372            .count()
373    };
374    let mut inner_dot = false;
375    if digits(at) > 0 {
376        at += digits(at);
377        while bytes.get(at) == Some(&b'.') && digits(at + 1) > 0 {
378            inner_dot = true;
379            at += 1 + digits(at + 1);
380        }
381    } else {
382        let letters = bytes[at..]
383            .iter()
384            .take_while(|b| b.is_ascii_alphabetic())
385            .count();
386        let roman = bytes[at..at + letters]
387            .iter()
388            .all(|b| b"ivxlcdmIVXLCDM".contains(b));
389        if letters == 1 || (roman && (1..=6).contains(&letters)) {
390            at += letters;
391        } else {
392            return 0;
393        }
394    }
395    if at == body_start || at > 12 {
396        return 0;
397    }
398    let close = match bytes.get(at) {
399        Some(b')') => {
400            at += 1;
401            true
402        }
403        Some(b'.') if !open => {
404            at += 1;
405            true
406        }
407        _ => false,
408    };
409    if !(close || (inner_dot && !open)) || (open && bytes.get(at - 1) != Some(&b')')) {
410        return 0;
411    }
412    let space = bytes[at..]
413        .iter()
414        .take_while(|b| b.is_ascii_whitespace())
415        .count();
416    if space == 0 || at + space >= bytes.len() {
417        return 0;
418    }
419    at + space
420}
421
422fn heading_level(style: &str) -> Option<u8> {
423    let level = style.strip_prefix("Heading")?.parse::<u8>().ok()?;
424    (1..=9).contains(&level).then_some(level)
425}
426
427/// Whether a paragraph and a block can be the same: cells pair with cells.
428fn compatible(paragraph: &Paragraph, block: &Block) -> bool {
429    (paragraph.kind == Kind::Cell) == (block.kind == Kind::Cell)
430}
431
432/// Aligns paragraphs and blocks: equal text first, then, in each stretch
433/// that differs, the most similar compatible pairs in order, then leftovers
434/// by position.
435fn align(paragraphs: &[Paragraph], blocks: &[Block]) -> Vec<Edit> {
436    let old_keys: Vec<String> = paragraphs.iter().map(|p| key(&p.text)).collect();
437    let new_keys: Vec<String> = blocks.iter().map(|b| key(&b.text())).collect();
438    let mut edits = Vec::new();
439    let mut last: Option<usize> = None;
440    for op in capture_diff_slices(Algorithm::Patience, &old_keys, &new_keys) {
441        let (tag, olds, news) = op.as_tag_tuple();
442        if tag == DiffTag::Equal {
443            for (p, b) in olds.zip(news) {
444                edits.push(Edit::Pair(p, b));
445                last = Some(p);
446            }
447            continue;
448        }
449        let olds: Vec<usize> = olds.collect();
450        let news: Vec<usize> = news.collect();
451        let matched = pair(&olds, &news, |p, b| {
452            if !compatible(&paragraphs[p], &blocks[b]) {
453                return None;
454            }
455            let s = similarity(&old_keys[p], &new_keys[b]);
456            (s >= PAIR_SIMILARITY).then_some(s)
457        });
458        let (mut i, mut j) = (0, 0);
459        for (mi, mj) in matched
460            .into_iter()
461            .chain(std::iter::once((olds.len(), news.len())))
462        {
463            while i < mi && j < mj && compatible(&paragraphs[olds[i]], &blocks[news[j]]) {
464                edits.push(Edit::Pair(olds[i], news[j]));
465                last = Some(olds[i]);
466                i += 1;
467                j += 1;
468            }
469            for &p in &olds[i..mi] {
470                edits.push(Edit::Delete(p));
471            }
472            for &b in &news[j..mj] {
473                edits.push(Edit::Insert(b, last));
474            }
475            if mi < olds.len() && mj < news.len() {
476                edits.push(Edit::Pair(olds[mi], news[mj]));
477                last = Some(olds[mi]);
478            }
479            i = mi + 1;
480            j = mj + 1;
481        }
482    }
483    edits
484}
485
486/// Weighted longest common subsequence of `olds` and `news` under `score`.
487fn pair(
488    olds: &[usize],
489    news: &[usize],
490    score: impl Fn(usize, usize) -> Option<f64>,
491) -> Vec<(usize, usize)> {
492    let (k, m) = (olds.len(), news.len());
493    if k == 0 || m == 0 || k * m > MAX_PAIRINGS {
494        return Vec::new();
495    }
496    let scores: Vec<Vec<Option<f64>>> = olds
497        .iter()
498        .map(|&p| news.iter().map(|&b| score(p, b)).collect())
499        .collect();
500    let mut best = vec![vec![0.0f64; m + 1]; k + 1];
501    for i in (0..k).rev() {
502        for j in (0..m).rev() {
503            let take = scores[i][j].map_or(f64::MIN, |s| s + best[i + 1][j + 1]);
504            best[i][j] = take.max(best[i + 1][j]).max(best[i][j + 1]);
505        }
506    }
507    let mut out = Vec::new();
508    let (mut i, mut j) = (0, 0);
509    while i < k && j < m {
510        if let Some(s) = scores[i][j]
511            && (best[i][j] - (s + best[i + 1][j + 1])).abs() < 1e-9
512        {
513            out.push((i, j));
514            i += 1;
515            j += 1;
516        } else if (best[i][j] - best[i + 1][j]).abs() < 1e-9 {
517            i += 1;
518        } else {
519            j += 1;
520        }
521    }
522    out
523}
524
525/// The paragraph's new text: the block's, after the paragraph's own typed
526/// numbering when it has some.
527fn rewritten(paragraph: &Paragraph, block: &Block) -> String {
528    let text = block.text();
529    let own = enumerator_len(&paragraph.text);
530    if own == 0 {
531        return text;
532    }
533    let theirs = enumerator_len(&text);
534    format!("{}{}", &paragraph.text[..own], &text[theirs..])
535}
536
537/// The plan's operations. Operation ids are `edit:N`, N the edit's index.
538fn operations(
539    paragraphs: &[Paragraph],
540    blocks: &[Block],
541    edits: &[Edit],
542    styles: &HashSet<String>,
543    whole: &HashSet<usize>,
544    dropped: &HashSet<usize>,
545) -> Vec<Operation> {
546    let at = |p: usize| Selector::Index {
547        index: paragraphs[p].index,
548        story: None,
549    };
550    // Paragraphs the plan deletes: a new paragraph cannot anchor on them.
551    let gone: HashSet<usize> = edits
552        .iter()
553        .enumerate()
554        .filter(|(entry, _)| !dropped.contains(entry))
555        .filter_map(|(entry, edit)| match *edit {
556            Edit::Delete(p) if paragraphs[p].kind != Kind::Cell => Some(p),
557            Edit::Pair(p, _) if whole.contains(&entry) => Some(p),
558            _ => None,
559        })
560        .collect();
561    let stays = |p: &usize| !gone.contains(p);
562    // A paragraph replaced whole still anchors: its new paragraph sits
563    // right after it, so what the Markdown adds after it follows
564    // (#1670, round 8).
565    let replaced: HashSet<usize> = edits
566        .iter()
567        .enumerate()
568        .filter(|(entry, _)| !dropped.contains(entry) && whole.contains(entry))
569        .filter_map(|(_, edit)| match *edit {
570            Edit::Pair(p, _) => Some(p),
571            _ => None,
572        })
573        .collect();
574    let anchors = |p: &usize| stays(p) || replaced.contains(p);
575    // A paragraph for `block` between paragraph positions `after` and
576    // `next`: placed next to a staying neighbour, with the properties of the
577    // nearest staying paragraph of the block's kind.
578    let insert = |block: &Block, after: Option<usize>, next: Option<usize>| {
579        let after = after
580            .filter(anchors)
581            .or_else(|| after.and_then(|a| (0..a).rev().find(|p| anchors(p))));
582        let next = next
583            .filter(anchors)
584            .or_else(|| next.and_then(|n| (n + 1..paragraphs.len()).find(|p| anchors(p))));
585        let (anchor, side) = match (after, next) {
586            (Some(a), _) => (a, Side::After),
587            (None, Some(n)) => (n, Side::Before),
588            (None, None) => return None,
589        };
590        let nearest = |fits: &dyn Fn(Kind) -> bool| {
591            (0..paragraphs.len())
592                .filter(|p| stays(p) && fits(paragraphs[*p].kind))
593                .min_by_key(|p| p.abs_diff(anchor))
594        };
595        let same = nearest(&|kind| kind == block.kind);
596        let (like, style) = match (same, block.kind) {
597            (Some(like), _) => (like, None),
598            (None, Kind::Heading(level)) => {
599                let name = format!("heading {level}");
600                let style = styles.contains(&name).then_some(name);
601                let like = nearest(&|kind| matches!(kind, Kind::Heading(_)))
602                    .filter(|_| style.is_some())
603                    .or_else(|| nearest(&|kind| kind == Kind::Plain))
604                    .unwrap_or(anchor);
605                (like, style)
606            }
607            (None, _) => (nearest(&|kind| kind == Kind::Plain).unwrap_or(anchor), None),
608        };
609        Some(OperationKind::InsertParagraph {
610            paragraph: at(anchor),
611            position: side,
612            runs: block.runs.clone(),
613            like: (like != anchor).then(|| at(like)),
614            style,
615            comment: None,
616        })
617    };
618    let mut operations = Vec::new();
619    for (entry, edit) in edits.iter().enumerate() {
620        if dropped.contains(&entry) {
621            continue;
622        }
623        let id = Some(format!("edit:{entry}"));
624        match *edit {
625            Edit::Pair(p, b) => {
626                let paragraph = &paragraphs[p];
627                let block = &blocks[b];
628                if key(&paragraph.text) == key(&block.text()) {
629                    continue;
630                }
631                if !whole.contains(&entry) {
632                    operations.push(Operation {
633                        id,
634                        group: None,
635                        kind: OperationKind::Rewrite {
636                            paragraph: at(p),
637                            text: rewritten(paragraph, block),
638                            comment: None,
639                        },
640                    });
641                    continue;
642                }
643                // The paragraph replaced whole: the new one right after it,
644                // with its properties, then the old one deleted. A new
645                // paragraph beside a deleted one takes its place, in its
646                // cell or story (#1668).
647                operations.push(Operation {
648                    id: Some(format!("edit:{entry}:new")),
649                    group: None,
650                    kind: OperationKind::InsertParagraph {
651                        paragraph: at(p),
652                        position: Side::After,
653                        runs: block.runs.clone(),
654                        like: None,
655                        style: None,
656                        comment: None,
657                    },
658                });
659                operations.push(Operation {
660                    id,
661                    group: None,
662                    kind: OperationKind::DeleteParagraph {
663                        paragraph: at(p),
664                        comment: None,
665                    },
666                });
667            }
668            Edit::Delete(p) => {
669                let kind = if paragraphs[p].kind == Kind::Cell {
670                    // A cell keeps its paragraph; its text goes.
671                    OperationKind::Rewrite {
672                        paragraph: at(p),
673                        text: String::new(),
674                        comment: None,
675                    }
676                } else {
677                    OperationKind::DeleteParagraph {
678                        paragraph: at(p),
679                        comment: None,
680                    }
681                };
682                operations.push(Operation {
683                    id,
684                    group: None,
685                    kind,
686                });
687            }
688            Edit::Insert(b, after) => {
689                let block = &blocks[b];
690                if block.kind == Kind::Cell {
691                    continue;
692                }
693                let next = edits[entry..].iter().find_map(|e| match e {
694                    Edit::Pair(p, _) | Edit::Delete(p) => Some(*p),
695                    Edit::Insert(..) => None,
696                });
697                if let Some(kind) = insert(block, after, next) {
698                    operations.push(Operation {
699                        id,
700                        group: None,
701                        kind,
702                    });
703                }
704            }
705        }
706    }
707    operations
708}
709
710/// The Markdown's blocks in order, and whether it has footnotes.
711fn blocks(markdown: &str) -> (Vec<Block>, bool) {
712    let options = Options::ENABLE_TABLES
713        | Options::ENABLE_FOOTNOTES
714        | Options::ENABLE_STRIKETHROUGH
715        | Options::ENABLE_TASKLISTS
716        | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS;
717    let mut out: Vec<Block> = Vec::new();
718    let mut open: Option<Block> = None;
719    let mut notes = false;
720    let mut skip = 0u32;
721    let mut lists = 0u32;
722    let mut heading: Option<u8> = None;
723    let mut cell = false;
724    let mut code = false;
725    let (mut bold, mut italic) = (0u32, 0u32);
726    let close = |open: &mut Option<Block>, out: &mut Vec<Block>| {
727        if let Some(block) = open.take()
728            && !block.text().trim().is_empty()
729        {
730            out.push(block);
731        }
732    };
733    for event in Parser::new_ext(markdown, options) {
734        if skip > 0 {
735            match event {
736                Event::Start(
737                    Tag::FootnoteDefinition(_) | Tag::MetadataBlock(_) | Tag::Image { .. },
738                ) => {
739                    skip += 1;
740                }
741                Event::End(
742                    TagEnd::FootnoteDefinition | TagEnd::MetadataBlock(_) | TagEnd::Image,
743                ) => {
744                    skip -= 1;
745                }
746                _ => {}
747            }
748            continue;
749        }
750        let kind = || match heading {
751            Some(level) => Kind::Heading(level),
752            None if cell => Kind::Cell,
753            None if lists > 0 => Kind::List,
754            None => Kind::Plain,
755        };
756        match event {
757            Event::Start(Tag::FootnoteDefinition(_)) => {
758                close(&mut open, &mut out);
759                notes = true;
760                skip = 1;
761            }
762            Event::Start(Tag::MetadataBlock(_) | Tag::Image { .. }) => skip = 1,
763            Event::Start(Tag::Heading { level, .. }) => {
764                close(&mut open, &mut out);
765                heading = Some(match level {
766                    HeadingLevel::H1 => 1,
767                    HeadingLevel::H2 => 2,
768                    HeadingLevel::H3 => 3,
769                    HeadingLevel::H4 => 4,
770                    HeadingLevel::H5 => 5,
771                    HeadingLevel::H6 => 6,
772                });
773            }
774            Event::End(TagEnd::Heading(_)) => {
775                close(&mut open, &mut out);
776                heading = None;
777            }
778            Event::Start(Tag::List(_)) => {
779                close(&mut open, &mut out);
780                lists += 1;
781            }
782            Event::End(TagEnd::List(_)) => {
783                close(&mut open, &mut out);
784                lists = lists.saturating_sub(1);
785            }
786            Event::Start(Tag::TableCell) => {
787                close(&mut open, &mut out);
788                cell = true;
789                open = Some(Block {
790                    kind: Kind::Cell,
791                    runs: Vec::new(),
792                });
793            }
794            Event::End(TagEnd::TableCell) => {
795                close(&mut open, &mut out);
796                cell = false;
797            }
798            Event::Start(Tag::CodeBlock(_)) => {
799                close(&mut open, &mut out);
800                code = true;
801            }
802            Event::End(TagEnd::CodeBlock) => {
803                close(&mut open, &mut out);
804                code = false;
805            }
806            Event::Start(
807                Tag::Paragraph | Tag::Item | Tag::BlockQuote(_) | Tag::Table(_) | Tag::HtmlBlock,
808            )
809            | Event::End(
810                TagEnd::Paragraph
811                | TagEnd::Item
812                | TagEnd::BlockQuote(_)
813                | TagEnd::Table
814                | TagEnd::HtmlBlock,
815            )
816            | Event::Rule => close(&mut open, &mut out),
817            Event::Start(Tag::Strong) => bold += 1,
818            Event::End(TagEnd::Strong) => bold = bold.saturating_sub(1),
819            Event::Start(Tag::Emphasis) => italic += 1,
820            Event::End(TagEnd::Emphasis) => italic = italic.saturating_sub(1),
821            Event::Text(text) | Event::Code(text) => {
822                let pieces: Vec<&str> = if code {
823                    text.split('\n').collect()
824                } else {
825                    vec![&text]
826                };
827                for (n, piece) in pieces.iter().enumerate() {
828                    if code && n > 0 {
829                        close(&mut open, &mut out);
830                    }
831                    let block = open.get_or_insert_with(|| Block {
832                        kind: kind(),
833                        runs: Vec::new(),
834                    });
835                    push_run(
836                        block,
837                        &piece.replace(['\t', '\r'], " "),
838                        bold > 0,
839                        italic > 0,
840                    );
841                }
842            }
843            Event::SoftBreak | Event::HardBreak => {
844                if let Some(block) = &mut open {
845                    push_run(block, " ", bold > 0, italic > 0);
846                }
847            }
848            Event::InlineHtml(html) if html.to_ascii_lowercase().starts_with("<br") => {
849                if let Some(block) = &mut open {
850                    push_run(block, " ", bold > 0, italic > 0);
851                }
852            }
853            _ => {}
854        }
855    }
856    close(&mut open, &mut out);
857    (out, notes)
858}
859
860/// Appends text to the block, joining the last run when its formatting is
861/// the same.
862fn push_run(block: &mut Block, text: &str, bold: bool, italic: bool) {
863    if text.is_empty() {
864        return;
865    }
866    let (bold, italic) = (bold.then_some(true), italic.then_some(true));
867    match block.runs.last_mut() {
868        Some(last) if last.bold == bold && last.italic == italic => last.text.push_str(text),
869        _ => block.runs.push(RunSpec {
870            text: text.to_string(),
871            bold,
872            italic,
873            ..RunSpec::default()
874        }),
875    }
876}
877
878#[cfg(test)]
879#[cfg_attr(all(coverage_nightly, test), coverage(off))]
880mod tests {
881    use super::*;
882
883    #[test]
884    fn typed_numbering_is_found() {
885        for (text, number) in [
886            ("1. Definitions", "1. "),
887            ("1.\tDefinitions", "1.\t"),
888            ("1.2 Scope", "1.2 "),
889            ("(a) the Buyer", "(a) "),
890            ("b) the Seller", "b) "),
891            ("iv. Remedies", "iv. "),
892            ("IV. Remedies", "IV. "),
893            ("A. Parties", "A. "),
894            ("A cat sat.", ""),
895            ("I am here.", ""),
896            ("2024 was a year.", ""),
897            ("(see below) text", ""),
898            ("1.", ""),
899            ("Intro", ""),
900        ] {
901            assert_eq!(&text[..enumerator_len(text)], number, "{text}");
902        }
903    }
904
905    #[test]
906    fn keys_ignore_numbering_spacing_and_symbols() {
907        assert_eq!(key("1.\tDefinitions  apply"), "Definitions apply");
908        assert_eq!(key("x \u{FFFC} y"), "x y");
909    }
910
911    #[test]
912    fn blocks_have_kinds_and_runs() {
913        let (blocks, notes) = blocks(
914            "# Title\n\nSome **bold** text.[^1]\n\n- item\n\n| a | b |\n|---|---|\n| 1 | 2 |\n\n```\nx\ny\n```\n\n![alt](i.png)\n\n[^1]: note\n",
915        );
916        let summary: Vec<(Kind, String)> = blocks.iter().map(|b| (b.kind, b.text())).collect();
917        assert_eq!(
918            summary,
919            [
920                (Kind::Heading(1), "Title".to_string()),
921                (Kind::Plain, "Some bold text.".to_string()),
922                (Kind::List, "item".to_string()),
923                (Kind::Cell, "a".to_string()),
924                (Kind::Cell, "b".to_string()),
925                (Kind::Cell, "1".to_string()),
926                (Kind::Cell, "2".to_string()),
927                (Kind::Plain, "x".to_string()),
928                (Kind::Plain, "y".to_string()),
929            ]
930        );
931        assert_eq!(blocks[1].runs[1].bold, Some(true));
932        assert!(notes);
933    }
934
935    #[test]
936    fn a_rewrite_keeps_the_paragraphs_own_numbering() {
937        let paragraph = Paragraph {
938            index: 0,
939            text: "3.\tPayment terms".to_string(),
940            kind: Kind::Plain,
941        };
942        let block = |text: &str| Block {
943            kind: Kind::List,
944            runs: vec![RunSpec {
945                text: text.to_string(),
946                ..RunSpec::default()
947            }],
948        };
949        assert_eq!(
950            rewritten(&paragraph, &block("Payment and terms")),
951            "3.\tPayment and terms"
952        );
953        assert_eq!(rewritten(&paragraph, &block("4. Payment")), "3.\tPayment");
954    }
955}
956#[cfg(test)]
957#[cfg_attr(all(coverage_nightly, test), coverage(off))]
958mod markdown_pairing_boundary_tests {
959    use super::*;
960
961    fn block(text: &str, kind: Kind) -> Block {
962        Block {
963            kind,
964            runs: vec![RunSpec {
965                text: text.to_string(),
966                ..RunSpec::default()
967            }],
968        }
969    }
970
971    fn edit_view(edits: &[Edit]) -> Vec<(char, usize, Option<usize>)> {
972        edits
973            .iter()
974            .map(|e| match e {
975                Edit::Pair(p, b) => ('P', *p, Some(*b)),
976                Edit::Insert(b, after) => ('I', *b, *after),
977                Edit::Delete(p) => ('D', *p, None),
978            })
979            .collect()
980    }
981
982    #[test]
983    fn ordered_pairing_boundaries_keep_every_authored_index_once() {
984        let a = (0..50)
985            .map(|i| Paragraph {
986                index: i,
987                text: format!("old-{i}"),
988                kind: Kind::Plain,
989            })
990            .collect::<Vec<_>>();
991        for count in [0, 49, 50, 51] {
992            let b = (0..count)
993                .map(|i| block(&format!("new-{i}"), Kind::Plain))
994                .collect::<Vec<_>>();
995            let edits = align(&a, &b);
996            let mut expected = (0..count.min(50))
997                .map(|i| ('P', i, Some(i)))
998                .collect::<Vec<_>>();
999            if count < 50 {
1000                expected.extend((count..50).map(|i| ('D', i, None)));
1001            }
1002            if count > 50 {
1003                expected.push(('I', 50, Some(49)));
1004            }
1005            assert_eq!(edit_view(&edits), expected, "count {count}");
1006            assert_eq!(
1007                a.iter().map(|p| p.text.as_str()).collect::<Vec<_>>(),
1008                (0..50)
1009                    .map(|i| format!("old-{i}"))
1010                    .collect::<Vec<_>>()
1011                    .iter()
1012                    .map(String::as_str)
1013                    .collect::<Vec<_>>()
1014            );
1015        }
1016        assert_eq!(
1017            edit_view(&align(&[], &[block("new", Kind::Plain)])),
1018            vec![('I', 0, None)]
1019        );
1020        let paragraphs = vec![
1021            Paragraph {
1022                index: 0,
1023                text: "old cell".to_string(),
1024                kind: Kind::Cell,
1025            },
1026            Paragraph {
1027                index: 1,
1028                text: "anchor".to_string(),
1029                kind: Kind::Plain,
1030            },
1031        ];
1032        assert_eq!(
1033            edit_view(&align(
1034                &paragraphs,
1035                &[block("new body", Kind::Plain), block("anchor", Kind::Plain)]
1036            )),
1037            vec![('D', 0, None), ('I', 0, None), ('P', 1, Some(1))]
1038        );
1039    }
1040
1041    #[test]
1042    fn weighted_pairing_skips_weaker_conflicts_without_crossing_source_owners() {
1043        let indices = [0, 1, 2];
1044        let score = |a: usize, b: usize| match (a, b) {
1045            (0, 0) => Some(0.4),
1046            (0, 1) => Some(0.9),
1047            (1, 1) => Some(0.2),
1048            (2, 2) => Some(1.0),
1049            _ => None,
1050        };
1051        assert_eq!(pair(&indices, &indices, score), vec![(0, 1), (2, 2)]);
1052        assert_eq!(
1053            pair(&indices, &indices, |a, b| if a == 1 && b == 0 {
1054                Some(1.0)
1055            } else {
1056                None
1057            }),
1058            vec![(1, 0)]
1059        );
1060        assert_eq!(
1061            pair(&indices, &indices, |_, _| None),
1062            Vec::<(usize, usize)>::new()
1063        );
1064        assert_eq!(pair(&[], &indices, score), Vec::<(usize, usize)>::new());
1065        assert_eq!(pair(&indices, &[], score), Vec::<(usize, usize)>::new());
1066    }
1067
1068    #[test]
1069    fn malformed_numbering_remains_literal_and_normalized_line_breaks_keep_run_formatting() {
1070        for text in [
1071            "1234567890123. text",
1072            "1.x",
1073            "1. ",
1074            "(a. text",
1075            "(1.2 text",
1076            "vvvvvvv. text",
1077        ] {
1078            assert_eq!(enumerator_len(text), 0, "{text}");
1079            let p = Paragraph {
1080                index: 0,
1081                text: text.to_string(),
1082                kind: Kind::Plain,
1083            };
1084            assert_eq!(
1085                rewritten(&p, &block("replacement", Kind::Plain)),
1086                "replacement"
1087            );
1088        }
1089        for (source, expected) in [
1090            ("left  \nright", "left right"),
1091            ("left<br>right", "left right"),
1092            ("**left<br>right**", "left right"),
1093        ] {
1094            let (parsed, notes) = blocks(source);
1095            assert!(!notes);
1096            assert_eq!(parsed.len(), 1);
1097            assert_eq!(parsed[0].kind, Kind::Plain);
1098            assert_eq!(parsed[0].text(), expected);
1099            if source.starts_with("**") {
1100                assert!(parsed[0].runs.iter().all(|run| run.bold == Some(true)));
1101            }
1102        }
1103    }
1104}