Skip to main content

jubarte_edit/markdown/
redline.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! The Markdown side of the Word redline task.
6//!
7//! A redline takes two [`Source`] documents (`.docx` bytes or Markdown
8//! strings), turns each into a Word package, and feeds the comparator
9//! the bodies, returning a tracked-changes `.docx`. Markdown against a
10//! Word document applies the Markdown's edits to that document
11//! ([`apply_markdown`]) so direct formatting, fields, section breaks
12//! and empty paragraphs the Markdown cannot hold stay as they were.
13//! Markdown against Markdown is written to Word first
14//! ([`markdown_to_docx`]).
15//!
16//! Backs `jubarte compare` / `jubarte redline`, the Markdown input of
17//! [`crate::text_diff`], and the Python / WASM
18//! [`crate::markdown::redline()`] binding.
19
20use super::{
21    DocxOptions, ImageLoader, MarkdownError, PageSize, TrackChanges, apply_markdown,
22    markdown_to_docx,
23};
24use crate::comparer::WmlComparerSettings;
25use crate::document_comparer::compare_documents_with_settings;
26
27/// A document side of a comparison: either a `.docx` package or a
28/// Markdown text. Backed onto [`crate::markdown::redline()`] from the
29/// redline command line and from the Python / WASM bindings.
30#[derive(Clone, Copy, Debug)]
31pub enum Source<'a> {
32    /// A `.docx` package bytes.
33    Docx(&'a [u8]),
34    /// Markdown text.
35    Markdown(&'a str),
36}
37
38/// How [`redline`] reads and compares two [`Source`] documents.
39///
40/// Defaults: [`WmlComparerSettings::default`] (author
41/// `"Open-Xml-PowerTools"`; the CLI passes `Jubarte` and the Python and
42/// WebAssembly bindings their own `Redline`,
43/// `DATE "1970-01-01T00:00:00Z"` for reproducible output, Word's own
44/// detail threshold); no reference document, no CriticMarkup recognition,
45/// no image loader.
46#[derive(Clone, Default)]
47pub struct RedlineOptions<'a> {
48    /// The comparer's settings: author, date, detail threshold, mode,
49    /// move detection, format-change detection, the input budget for
50    /// [`crate::admission`]. See [`crate::comparer::WmlComparerSettings`].
51    pub settings: WmlComparerSettings,
52    /// Styles, page setup, headers and footers when both sides are
53    /// Markdown; built-in styles when `None`. Against a Word document the
54    /// Markdown is applied to that document instead, so this only affects
55    /// the Markdown / Markdown case.
56    pub reference: Option<&'a [u8]>,
57    /// Read CriticMarkup in a Markdown side as tracked changes and
58    /// comments. Off by default: a Markdown document being compared is
59    /// treated as plain text.
60    pub critic: bool,
61    /// The bytes of each image a Markdown side names; `None` writes every
62    /// image as its alt text.
63    pub images: Option<ImageLoader<'a>>,
64}
65
66impl std::fmt::Debug for RedlineOptions<'_> {
67    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        f.debug_struct("RedlineOptions")
69            .field("settings", &self.settings)
70            .field("reference", &self.reference.map(<[u8]>::len))
71            .field("critic", &self.critic)
72            .field("images", &self.images.is_some())
73            .finish()
74    }
75}
76
77/// Compares `original` against `modified` and returns a Word
78/// tracked-changes document: the original with every difference as a
79/// revision, as
80/// [`crate::document_comparer::compare_documents_with_settings`] writes
81/// it. Backs `jubarte compare`, `jubarte redline`, and the Python / WASM
82/// redline bindings.
83///
84/// Either side may be Markdown. Against a Word document, the Markdown's
85/// edits are applied to that Word document ([`apply_markdown`]), so what
86/// Markdown cannot represent (empty paragraphs, fields, section breaks,
87/// direct formatting) stays as it was. Two Markdown documents are first
88/// written to Word ([`markdown_to_docx`]).
89///
90/// # Errors
91///
92/// [`MarkdownError::Package`] when a Word side paired with Markdown cannot
93/// be admitted or read by [`apply_markdown`], or when the comparer's
94/// `compare_documents_with_settings` call fails; what [`markdown_to_docx`]
95/// returns (a bad reference document is [`MarkdownError::Reference`]) when
96/// both sides are Markdown.
97///
98/// ```
99/// use jubarte_edit::markdown::{RedlineOptions, Source, redline};
100///
101/// let docx = redline(
102///     Source::Markdown("Payment in 30 days.\n"),
103///     Source::Markdown("Payment in 45 days.\n"),
104///     &RedlineOptions::default(),
105/// )
106/// .unwrap();
107/// assert!(docx.starts_with(b"PK"));
108/// ```
109pub fn redline(
110    original: Source<'_>,
111    modified: Source<'_>,
112    options: &RedlineOptions<'_>,
113) -> Result<Vec<u8>, MarkdownError> {
114    let reference = options.reference;
115    let word = |source: Source<'_>| -> Result<Vec<u8>, MarkdownError> {
116        match source {
117            Source::Docx(docx) => Ok(docx.to_vec()),
118            Source::Markdown(markdown) => {
119                let written = markdown_to_docx(
120                    markdown,
121                    &DocxOptions {
122                        reference,
123                        critic: options.critic,
124                        track_changes: TrackChanges::All,
125                        author: options.settings.author_for_revisions.clone(),
126                        date: options.settings.date_time_for_revisions.clone(),
127                        author_fixed: false,
128                        date_fixed: false,
129                        images: options.images,
130                        page: PageSize::Letter,
131                        tracking: None,
132                        scholar: false,
133                    },
134                )?;
135                Ok(written.docx)
136            }
137        }
138    };
139    // Markdown against Word: the Markdown's edits are applied to the Word
140    // document, so all it cannot say (empty paragraphs, fields, section
141    // breaks, direct formatting) stays as it was.
142    let (original, modified) = match (original, modified) {
143        (Source::Docx(docx), Source::Markdown(markdown)) => {
144            let patched = apply_markdown(docx, markdown)?;
145            (docx.to_vec(), patched.docx)
146        }
147        (Source::Markdown(markdown), Source::Docx(docx)) => {
148            let patched = apply_markdown(docx, markdown)?;
149            (patched.docx, docx.to_vec())
150        }
151        (original, modified) => (word(original)?, word(modified)?),
152    };
153    compare_documents_with_settings(&original, &modified, &options.settings)
154        .map_err(|e| MarkdownError::Package(format!("comparing: {e}")))
155}
156
157#[cfg(test)]
158mod debug_shape_tests {
159    use super::*;
160
161    #[test]
162    fn default_redline_options_debug_names_its_flags() {
163        // Moved from markdown's options test (T4.6): the Debug shape this
164        // type hand-writes is an edit-layer contract.
165        let debug = format!("{:?}", RedlineOptions::default());
166        assert!(
167            debug.contains("critic: false") && debug.contains("images: false"),
168            "{debug}"
169        );
170    }
171}