1use 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
34const PAIR_SIMILARITY: f64 = 0.3;
37
38const MAX_PAIRINGS: usize = 2_500;
41
42#[derive(Clone, Debug, PartialEq, Eq)]
49pub struct Patched {
50 pub docx: Vec<u8>,
52 pub warnings: Vec<String>,
58}
59
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63enum Kind {
64 Heading(u8),
65 List,
66 Cell,
67 Plain,
68}
69
70#[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#[derive(Clone, Debug)]
85struct Paragraph {
86 index: usize,
87 text: String,
88 kind: Kind,
89}
90
91pub fn apply_markdown(docx: &[u8], markdown: &str) -> Result<Patched, MarkdownError> {
122 apply_markdown_exact(docx, markdown, false)
123}
124
125pub 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 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(¶graphs, &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 if strict {
187 return Err(MarkdownError::Package(left_out));
188 }
189 warnings.push(left_out);
190 }
191 }
192
193 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(¶graphs, &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 let failed: std::collections::BTreeMap<usize, String> = error
234 .outcomes
235 .iter()
236 .filter(|o| o.status == "failed")
237 .chain(
238 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], ¶graphs, &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
274fn 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 .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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
316enum Edit {
317 Pair(usize, usize),
319 Insert(usize, Option<usize>),
322 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(¶graphs[p].text)
346 ),
347 }
348}
349
350fn 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
358fn 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
427fn compatible(paragraph: &Paragraph, block: &Block) -> bool {
429 (paragraph.kind == Kind::Cell) == (block.kind == Kind::Cell)
430}
431
432fn 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(¶graphs[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(¶graphs[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
486fn 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
525fn rewritten(paragraph: &Paragraph, block: &Block) -> String {
528 let text = block.text();
529 let own = enumerator_len(¶graph.text);
530 if own == 0 {
531 return text;
532 }
533 let theirs = enumerator_len(&text);
534 format!("{}{}", ¶graph.text[..own], &text[theirs..])
535}
536
537fn 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 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 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 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 = ¶graphs[p];
627 let block = &blocks[b];
628 if key(¶graph.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 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 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
710fn 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
860fn 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\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(¶graph, &block("Payment and terms")),
951 "3.\tPayment and terms"
952 );
953 assert_eq!(rewritten(¶graph, &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 ¶graphs,
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}