Skip to main content

jubarte_markdown/markdown/
mod.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Markdown to Word.
6//!
7//! [`markdown_to_docx`](crate::markdown::markdown_to_docx) writes CommonMark, with GitHub's tables,
8//! strikethrough, task lists and footnotes, as a `.docx`. CriticMarkup in the
9//! Markdown becomes Word tracked changes and comments:
10//!
11//! | CriticMarkup | Word |
12//! | --- | --- |
13//! | `{++new++}` | inserted text (`w:ins`) |
14//! | `{--old--}` | deleted text (`w:del`) |
15//! | `{~~old~>new~~}` | deleted, then inserted text |
16//! | `{==text==}{>>note<<}` | a comment on `text` |
17//! | `{>>note<<}` after a change | a comment on the change |
18//! | `{==text==}` alone | highlighted text |
19//!
20//! A change can span paragraphs: the paragraph marks inside it are inserted
21//! or deleted too, so `A{++\n\nB++}` adds paragraph `B` after `A`. A block
22//! whose whole text is one change (`{++New paragraph.++}`) is inserted or
23//! deleted with its paragraph mark, as Word records a paragraph added or
24//! removed whole.
25//!
26//! Styles use Word's built-in ids (`Normal`, `Heading1`..`Heading6`,
27//! `Quote`, `ListParagraph`, `FootnoteText`, `Hyperlink`, `TableGrid`...)
28//! and pandoc's for code (`SourceCode`, `VerbatimChar`), so a reference
29//! document made by Word or by pandoc styles the output
30//! ([`DocxOptions::reference`](crate::markdown::DocxOptions::reference)).
31//!
32//! Backs `jubarte convert FILE.md`, `jubarte convert FILE.docx -t md`,
33//! `jubarte read`, the redline task's Markdown side
34//! (`jubarte::markdown::RedlineOptions`, `jubarte::markdown::redline()`) and
35//! the patch task (`Patch`, composed into the facade's markdown), plus
36//! the Python and WASM
37//! bindings over them.
38
39mod anchor;
40pub(crate) use crate::borders;
41#[doc(hidden)]
42pub mod critic;
43pub(crate) mod data_stores;
44#[doc(hidden)]
45pub mod diff;
46pub(crate) mod frames;
47mod from_docx;
48mod math;
49#[doc(hidden)]
50pub mod package;
51mod pages;
52mod repair;
53#[doc(hidden)]
54pub mod view_notes;
55mod view_stories;
56mod view_styles;
57#[doc(hidden)]
58pub mod write;
59#[doc(hidden)]
60pub mod xml;
61
62#[doc(hidden)]
63pub use anchor::plain_anchor_with_removed;
64pub use anchor::{plain_anchor, unescape_markdown};
65pub use diff::diff_markdown;
66pub use pages::paginate;
67pub use write::{image_targets, markdown_to_docx};
68
69#[doc(hidden)]
70pub use package::{ensure_footnotes_part, max_drawing_id};
71#[doc(hidden)]
72pub use write::read_picture;
73#[doc(hidden)]
74pub use xml::{Picture, drawing_xml};
75
76/// What happens to the tracked changes a Markdown / `.docx` document
77/// describes. Backs the `convert`, `read`, and `diff` CLI flags of the
78/// same names and pandoc's `--track-changes`.
79#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
80pub enum TrackChanges {
81    /// Keep tracked changes as tracked changes (the default).
82    #[default]
83    All,
84    /// Accept every change, as Word's Accept All does.
85    Accept,
86    /// Reject every change, as Word's Reject All does.
87    Reject,
88}
89
90impl TrackChanges {
91    /// Parses `"all"`, `"accept"` or `"reject"`, the values of pandoc's
92    /// `--track-changes`, and the `"accepted"` and `"rejected"` the CLI
93    /// takes for them too. Returns `None` for any other input.
94    pub fn parse(value: &str) -> Option<Self> {
95        match value {
96            "all" => Some(Self::All),
97            "accept" | "accepted" => Some(Self::Accept),
98            "reject" | "rejected" => Some(Self::Reject),
99            _ => None,
100        }
101    }
102}
103
104/// The page a Markdown document is written on when no reference
105/// document gives one. Backs the `convert --page` CLI flag and the
106/// Markdown path of the redline. Both sizes use one-inch margins;
107/// Word's own A4 template uses 2 cm margins, but jubarte changes only
108/// the page size the user asks for.
109#[derive(
110    Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
111)]
112#[serde(rename_all = "lowercase")]
113pub enum PageSize {
114    /// US Letter, 8.5 by 11 inches (the default, as Word's US template).
115    #[default]
116    Letter,
117    /// ISO A4, 210 by 297 mm.
118    A4,
119}
120
121impl PageSize {
122    /// Parses `"letter"` or `"a4"`, the values of the CLI's `--page`.
123    /// Returns `None` for any other input.
124    pub fn parse(value: &str) -> Option<Self> {
125        match value {
126            "letter" => Some(Self::Letter),
127            "a4" => Some(Self::A4),
128            _ => None,
129        }
130    }
131
132    /// Returns the name [`Self::parse`] reads (`"letter"` or `"a4"`).
133    pub fn as_str(self) -> &'static str {
134        match self {
135            Self::Letter => "letter",
136            Self::A4 => "a4",
137        }
138    }
139}
140
141/// Resolves the CriticMarkup in `markdown` as `track_changes` says:
142/// `Accept` keeps insertions and drops deletions, `Reject` the other way
143/// round; both keep highlighted text (`{==…==}`) and drop comments
144/// (`{>>…<<}`). `All` returns the Markdown as it is.
145///
146/// ```
147/// use jubarte_markdown::markdown::{TrackChanges, resolve_critic};
148///
149/// let text = "Due in {~~30~>45~~} days.{>>Agreed on the call.<<}";
150/// assert_eq!(resolve_critic(text, TrackChanges::Accept), "Due in 45 days.");
151/// assert_eq!(resolve_critic(text, TrackChanges::Reject), "Due in 30 days.");
152/// ```
153pub fn resolve_critic(markdown: &str, track_changes: TrackChanges) -> String {
154    match track_changes {
155        TrackChanges::All => markdown.to_string(),
156        TrackChanges::Accept => critic::resolve(markdown, true),
157        TrackChanges::Reject => critic::resolve(markdown, false),
158    }
159}
160
161/// Accepted text snapshots remove wholly deleted clause lines.
162#[doc(hidden)]
163pub fn accepted_clauses(markdown: &str) -> String {
164    critic::accept_clauses(markdown)
165}
166
167/// Callback that, given the path an image in a Markdown document
168/// names, returns the image bytes. Backs `convert --resource-path`
169/// and the Python / WASM image-loader binding; `None` falls back to the
170/// image's alt text.
171pub type ImageLoader<'a> = &'a dyn Fn(&str) -> Option<Vec<u8>>;
172
173/// How [`markdown_to_docx`] writes a Markdown document to a `.docx`.
174/// Defaults to Word-faithful settings: no reference document,
175/// `critic = true` (CriticMarkup is read as tracked changes),
176/// `track_changes = All`, author `"Jubarte"`, date pinned to
177/// `1970-01-01T00:00:00Z` (so the same Markdown writes the same bytes),
178/// no image loader, US Letter page size.
179#[derive(Clone)]
180pub struct DocxOptions<'a> {
181    /// A `.docx` whose styles, numbering, page setup, headers and footers
182    /// the output takes, as pandoc's `--reference-doc`; its text is not
183    /// used. `None` uses built-in styles on the page [`DocxOptions::page`]
184    /// names.
185    pub reference: Option<&'a [u8]>,
186    /// Read CriticMarkup as tracked changes and comments. Off, its
187    /// delimiters are text.
188    pub critic: bool,
189    /// Keep, accept or reject the tracked changes CriticMarkup describes.
190    pub track_changes: TrackChanges,
191    /// Author of the tracked changes and comments.
192    pub author: String,
193    /// Their date, `YYYY-MM-DDTHH:MM:SSZ`; fixed by default so the same
194    /// Markdown writes the same bytes.
195    pub date: String,
196    /// `author` names the changes and comments that name no one, even when
197    /// the front matter has an `author:` (an `--author` the user typed).
198    /// `false`: the front matter's wins over `author`.
199    pub author_fixed: bool,
200    /// `date` dates the undated changes and comments, even when the front
201    /// matter has a date (`last_modified:`, `modified:`, `date:`,
202    /// `created:`). `false`: the front matter's wins over `date`.
203    pub date_fixed: bool,
204    /// The bytes of each image the Markdown names. Without it, or when it
205    /// returns `None`, an image is written as its alt text.
206    pub images: Option<ImageLoader<'a>>,
207    /// The page size when there is no reference document. With a reference,
208    /// its page setup wins and a page other than the default is reported in
209    /// [`WrittenDocx::warnings`].
210    pub page: PageSize,
211    /// Word's Track Changes switch (`w:trackRevisions`) in the output:
212    /// `Some` sets it whatever the Markdown's `track_changes:` key says;
213    /// `None` follows the key, and without one keeps the reference's
214    /// setting (off without a reference).
215    pub tracking: Option<bool>,
216    /// Set the document as LaTeX's article class sets a manuscript: Latin
217    /// Modern Roman at 10pt on 12pt lines, justified, bold headings, and
218    /// the page number centered in the footer from page 2. Only what the
219    /// front matter leaves out: its own `styles:` entries, headers and
220    /// footers win.
221    pub scholar: bool,
222}
223
224impl Default for DocxOptions<'_> {
225    fn default() -> Self {
226        Self {
227            reference: None,
228            critic: true,
229            track_changes: TrackChanges::All,
230            author: "Jubarte".to_string(),
231            date: crate::document_comparer::DEFAULT_DATE.to_string(),
232            author_fixed: false,
233            date_fixed: false,
234            images: None,
235            page: PageSize::Letter,
236            tracking: None,
237            scholar: false,
238        }
239    }
240}
241
242/// [`DocxOptions`] as the Python and WebAssembly bindings pass them (JSON,
243/// every field optional).
244#[derive(serde::Deserialize)]
245#[serde(deny_unknown_fields)]
246struct DocxOptionsJson {
247    #[serde(default)]
248    page: PageSize,
249    author: Option<String>,
250    date: Option<String>,
251    critic: Option<bool>,
252    #[serde(alias = "trackChanges")]
253    track_changes: Option<String>,
254    tracking: Option<bool>,
255    #[serde(default)]
256    scholar: bool,
257}
258
259/// [`DocxOptions`] from the JSON the Python and WebAssembly bindings pass:
260/// `page`, `author`, `date`, `critic`, `track_changes` (`trackChanges`),
261/// `tracking` and `scholar`, each optional. An `author` or `date` given
262/// wins over the front matter's, as the CLI's flags do. Images are written
263/// as their alt text.
264///
265/// # Errors
266///
267/// A field the options do not have, or a value they do not take.
268pub fn docx_options_from_json<'a>(
269    json: &str,
270    reference: Option<&'a [u8]>,
271) -> Result<DocxOptions<'a>, String> {
272    let parsed: DocxOptionsJson = serde_json::from_str(json).map_err(|e| e.to_string())?;
273    let track_changes = match parsed.track_changes.as_deref() {
274        None => TrackChanges::All,
275        Some(value) => TrackChanges::parse(value)
276            .ok_or_else(|| format!("track_changes must be all, accept or reject, not {value:?}"))?,
277    };
278    let defaults = DocxOptions::default();
279    Ok(DocxOptions {
280        reference,
281        critic: parsed.critic.unwrap_or(defaults.critic),
282        track_changes,
283        author_fixed: parsed.author.is_some(),
284        author: parsed.author.unwrap_or(defaults.author),
285        date_fixed: parsed.date.is_some(),
286        date: parsed.date.unwrap_or(defaults.date),
287        page: parsed.page,
288        tracking: parsed.tracking,
289        scholar: parsed.scholar,
290        ..defaults
291    })
292}
293
294impl std::fmt::Debug for DocxOptions<'_> {
295    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
296        f.debug_struct("DocxOptions")
297            .field("reference", &self.reference.map(<[u8]>::len))
298            .field("critic", &self.critic)
299            .field("track_changes", &self.track_changes)
300            .field("author", &self.author)
301            .field("date", &self.date)
302            .field("images", &self.images.is_some())
303            .field("page", &self.page)
304            .field("tracking", &self.tracking)
305            .field("scholar", &self.scholar)
306            .finish()
307    }
308}
309
310/// How [`docx_to_markdown`] reads a `.docx`. Defaults to the plain
311/// Markdown conversion with all revisions kept; `<!-- page N of M -->`
312/// lines from Word's cached breaks come only with `ids` (the agent view).
313#[derive(Clone, Debug, PartialEq, Eq)]
314pub struct MarkdownOptions {
315    /// Active XML tag and attribute budgets, checked before tree construction.
316    pub input_limits: crate::admission::InputLimits,
317    /// `All` writes tracked changes and comments as CriticMarkup; `Accept`
318    /// and `Reject` write the text after Word's Accept All or Reject All,
319    /// without comments.
320    pub track_changes: TrackChanges,
321    /// Collect the document's raster pictures and name them in the Markdown
322    /// under this directory, as pandoc's `--extract-media`. `None` writes a
323    /// picture as its alt text.
324    pub extract_media: Option<String>,
325    /// Agent view: a YAML header, an id line before every block, Word's
326    /// ids on revisions and comments. Off, the plain conversion, unchanged.
327    pub ids: bool,
328    /// With `ids`: comments inline (`true`), or hidden with their ids on the
329    /// id line of the paragraph that holds them.
330    pub comments: bool,
331    /// With `ids`: the name printed as `source:` in the header; `None`
332    /// prints `(bytes)`.
333    pub source: Option<String>,
334    /// With `ids`: the text painted on each page by the layout pass
335    /// (`convert::RenderReport::pages`), for `<!-- page N of M -->` lines.
336    /// `None` falls back to Word's cached page breaks.
337    pub pages: Option<Vec<String>>,
338    /// With `ids` and no `pages`: write `<!-- page N of M -->` lines from
339    /// Word's cached breaks (`true`, the default), or no page lines at all;
340    /// the header's page count is unaffected.
341    pub page_markers: bool,
342    /// With `ids`: timestamps inline on notes when an author's marks and
343    /// comments have different recorded date forms, including local offsets.
344    /// An author with undated marks always gets explicit dated notes.
345    pub dates: bool,
346    /// With `ids`: which blocks of the body to print.
347    pub select: Option<Select>,
348}
349
350impl Default for MarkdownOptions {
351    fn default() -> Self {
352        Self {
353            input_limits: crate::admission::InputLimits::default(),
354            track_changes: TrackChanges::All,
355            extract_media: None,
356            ids: false,
357            comments: true,
358            source: None,
359            pages: None,
360            page_markers: true,
361            dates: false,
362            select: None,
363        }
364    }
365}
366
367/// Which blocks of the agent view to print. Backs the `read` and
368/// `edit` CLI flags `-p`, `--head`, `--tail`, and `--changed` (with
369/// `--by`).
370#[derive(Clone, Debug, PartialEq, Eq)]
371pub enum Select {
372    /// The first `n` blocks (`--head N`); a table is one block.
373    Head(usize),
374    /// The last `n` blocks (`--tail N`).
375    Tail(usize),
376    /// Paragraphs and tables by id, in document order (`-p`).
377    Picks(Vec<Pick>),
378    /// The blocks that carry a tracked change or a comment (`--changed`);
379    /// with `by`, only those with that author's marks (`by` is a handle
380    /// such as `AC`, with or without the `@`, or the author's full name).
381    Changed {
382        /// The author whose marks a block must hold.
383        by: Option<String>,
384    },
385}
386
387/// One item of a `-p` selection: a contiguous paragraph range (`pN`,
388/// `pN-pM`, `pN-`, `-pM`) or a whole table (`tN`).
389#[derive(Clone, Debug, PartialEq, Eq)]
390pub enum Pick {
391    /// `pN`, `pN-pM`, `pN-` (to the end, `to: None`), `-pM` (`from: 0`).
392    Paragraphs {
393        /// The first paragraph of the pick.
394        from: usize,
395        /// The last paragraph of the pick; `None` runs to the end.
396        to: Option<usize>,
397    },
398    /// `tN`: the whole table.
399    Table(usize),
400}
401
402/// Validates the author `--changed --by` names: a handle such as `AC` or
403/// `@AC` (one `@`, the handle right after it), or the full name. The CLI
404/// and the Python / WASM bindings route their check through here.
405///
406/// Returns the original (untrimmed outer whitespace removed) handle on
407/// success; an error string otherwise.
408pub fn author(by: &str) -> Result<&str, String> {
409    let by = by.trim();
410    let name = by.strip_prefix('@').unwrap_or(by);
411    if name.is_empty() || name.starts_with('@') || name.starts_with(char::is_whitespace) {
412        Err("needs an author: a handle such as AC, or the full name".into())
413    } else {
414        Ok(by)
415    }
416}
417
418impl Select {
419    /// Selects the right [`Select`] variant from `read`'s CLI flags:
420    /// `-p` (`paragraphs`), `--head`, `--tail`, `--changed` with
421    /// `--by`, in that order of precedence. Returns `Ok(None)` when none
422    /// is given.
423    ///
424    /// # Errors
425    ///
426    /// An error string when:
427    /// - `--by` is set without `--changed`;
428    /// - `--changed` is set with any of `-p` / `--head` / `--tail`;
429    /// - the `--by` value does not parse as an author
430    ///   ([`author`]);
431    /// - the `-p` spec does not parse as a paragraph / table selection
432    ///   ([`Self::parse`]).
433    pub fn from_flags(
434        paragraphs: Option<&str>,
435        head: Option<usize>,
436        tail: Option<usize>,
437        changed: bool,
438        by: Option<&str>,
439    ) -> Result<Option<Self>, String> {
440        if by.is_some() && !changed {
441            return Err("by needs changed".to_string());
442        }
443        if changed && (paragraphs.is_some() || head.is_some() || tail.is_some()) {
444            return Err("changed excludes paragraphs, head and tail".to_string());
445        }
446        let by = by.map(author).transpose()?;
447        Ok(match (paragraphs, head, tail) {
448            _ if changed => Some(Self::Changed {
449                by: by.map(str::to_string),
450            }),
451            (Some(spec), _, _) => Some(Self::parse(spec)?),
452            (None, Some(n), _) => Some(Self::Head(n)),
453            (None, None, Some(n)) => Some(Self::Tail(n)),
454            (None, None, None) => None,
455        })
456    }
457
458    /// `p2, p5-p7, p17-, -p1, t0`: comma-separated picks. A pick is a body
459    /// paragraph or a table, as the settled short ids spell them
460    /// ([`crate::ids::ShortId`]), or a range of paragraphs, which may be
461    /// open at one end (`p17-` to the end, `-p1` from the start). An expired
462    /// spelling (`12`) is refused with its settled one. The open ends are
463    /// transitional: the 17 October 2026 contract retires them (closed
464    /// `pN-pM` ranges only); commas stay option-level separators.
465    pub fn parse(spec: &str) -> Result<Self, String> {
466        use crate::ids::{ShortId, Step, Story};
467        // The refusal of `item`, naming the settled spelling when known.
468        let refused = |item: &str, hint: Option<String>| {
469            let hint = hint.map_or_else(String::new, |h| format!("; the settled spelling is {h}"));
470            format!("{item}: {SELECT_EXPECTED}{hint}")
471        };
472        // The body path `text` names.
473        let body = |item: &str, text: &str| match text.trim().parse::<ShortId>() {
474            Ok(ShortId::Block {
475                story: Story::Body,
476                path,
477            }) => Ok(path),
478            Ok(_) => Err(refused(item, None)),
479            Err(e) => Err(refused(
480                item,
481                crate::ids::hint_where(e.hint, |id| {
482                    matches!(
483                        id,
484                        ShortId::Block {
485                            story: Story::Body,
486                            ..
487                        }
488                    )
489                }),
490            )),
491        };
492        // The body paragraph an end of a range names; `None` when open.
493        let end = |item: &str, text: &str| {
494            if text.trim().is_empty() {
495                return Ok(None);
496            }
497            match body(item, text)?[..] {
498                [Step::Paragraph(n)] => Ok(Some(n)),
499                _ => Err(refused(item, None)),
500            }
501        };
502        // The settled spelling of a whole range whose ends are expired
503        // (`2-3` is `p2-p3`): `None` when an end has none, or the range
504        // would run backwards.
505        let settled_range = |from: &str, to: &str| {
506            let settle = |text: &str| -> Option<Option<usize>> {
507                let text = text.trim();
508                if text.is_empty() {
509                    return Some(None);
510                }
511                let spelled = match text.parse::<ShortId>() {
512                    Ok(_) => text.to_string(),
513                    Err(e) => crate::ids::hint_where(e.hint, |id| {
514                        matches!(
515                            id,
516                            ShortId::Block {
517                                story: Story::Body,
518                                ..
519                            }
520                        )
521                    })?,
522                };
523                match spelled.parse::<ShortId>() {
524                    Ok(ShortId::Block {
525                        story: Story::Body,
526                        path,
527                    }) => match path[..] {
528                        [Step::Paragraph(n)] => Some(Some(n)),
529                        _ => None,
530                    },
531                    _ => None,
532                }
533            };
534            let (from, to) = (settle(from)?, settle(to)?);
535            if from.is_none() && to.is_none() || matches!((from, to), (Some(a), Some(b)) if b < a) {
536                return None;
537            }
538            let spell = |n: Option<usize>| n.map_or_else(String::new, |n| format!("p{n}"));
539            Some(format!("{}-{}", spell(from), spell(to)))
540        };
541        let mut picks = Vec::new();
542        for item in spec.split(',').map(str::trim).filter(|s| !s.is_empty()) {
543            if let Some((from, to)) = item.split_once('-') {
544                let (Ok(from_end), Ok(to_end)) = (end(item, from), end(item, to)) else {
545                    return Err(refused(item, settled_range(from, to)));
546                };
547                let (from, to) = (from_end, to_end);
548                if from.is_none() && to.is_none() {
549                    return Err(refused(item, None));
550                }
551                let from = from.unwrap_or(0);
552                if to.is_some_and(|to| to < from) {
553                    return Err(format!("{item}: the range runs backwards"));
554                }
555                picks.push(Pick::Paragraphs { from, to });
556                continue;
557            }
558            picks.push(match body(item, item)?[..] {
559                [Step::Paragraph(n)] => Pick::Paragraphs {
560                    from: n,
561                    to: Some(n),
562                },
563                [Step::Table(n)] => Pick::Table(n),
564                _ => return Err(refused(item, None)),
565            });
566        }
567        if picks.is_empty() {
568            return Err("no paragraphs selected".to_string());
569        }
570        Ok(Self::Picks(picks))
571    }
572}
573
574/// The author and timestamp a `.docx` gives the changes and comments that
575/// name none, when no parameter does: its first `dc:creator` and its
576/// `dcterms:created`. `None` for each it does not tell (or bytes that are
577/// no package); the caller falls back to `Jubarte` and
578/// [`crate::document_comparer::DEFAULT_DATE`].
579///
580/// ```
581/// let (author, date) = jubarte_markdown::markdown::docx_stamp(b"not a docx");
582/// assert_eq!((author, date), (None, None));
583/// ```
584pub fn docx_stamp(docx: &[u8]) -> (Option<String>, Option<String>) {
585    from_docx::creator_created(docx)
586}
587
588/// The author and timestamp a Markdown document gives the changes and
589/// comments that name none, when no parameter does: its front matter
590/// (`author:`; `last_modified:`, else `modified:`, `date:`, `created:`),
591/// else the reference `.docx`'s creator and creation time ([`docx_stamp`]),
592/// each on its own. `None` for each neither tells: the caller falls back
593/// to `Jubarte` and now, as `jubarte convert` does.
594///
595/// ```
596/// let md = "---\nauthor: Ann\ncreated: 2026-03-02\n---\n\nText.\n";
597/// let (author, date) = jubarte_markdown::markdown::markdown_stamp(md, None);
598/// assert_eq!(author.as_deref(), Some("Ann"));
599/// assert_eq!(date.as_deref(), Some("2026-03-02T00:00:00Z"));
600/// assert_eq!(jubarte_markdown::markdown::markdown_stamp("Text.\n", None), (None, None));
601/// ```
602pub fn markdown_stamp(
603    markdown: &str,
604    reference: Option<&[u8]>,
605) -> (Option<String>, Option<String>) {
606    let front = view_notes::file_defaults(markdown);
607    let (creator, created) = reference.map(docx_stamp).unwrap_or_default();
608    (front.author.or(creator), front.date.or(created))
609}
610
611/// Why a `read -p` pick was refused.
612const SELECT_EXPECTED: &str = "expected pN, pN-pM or tN";
613
614/// A document read as Markdown.
615#[derive(Clone, Debug, Default, PartialEq, Eq)]
616pub struct ReadDocx {
617    /// The Markdown, with CriticMarkup when changes are kept.
618    pub markdown: String,
619    /// Pictures to write under [`MarkdownOptions::extract_media`]: file
620    /// name and bytes, sorted by name.
621    pub media: Vec<(String, Vec<u8>)>,
622    /// The body paragraphs [`MarkdownOptions::select`] kept (`N` of `pN`,
623    /// ascending); `None` without a selection.
624    pub selected: Option<Vec<usize>>,
625    /// The header, footer and note stories (`header1`, `footnotes`) a
626    /// `--changed` selection keeps for their changes; empty otherwise.
627    pub selected_stories: Vec<String>,
628}
629
630/// Reads a `.docx` as Markdown: headings, emphasis, links, lists,
631/// tables, footnotes and equations (as LaTeX), with tracked changes and
632/// comments as CriticMarkup (`{++new++}`, `{--old--}`, `{~~old~>new~~}`,
633/// `{==text==}{>>note<<}`), each change followed by its author and
634/// date. Backs the Markdown output of `jubarte convert FILE.docx -t md`
635/// and the Python / WASM `docx_to_markdown` binding.
636///
637/// # Errors
638///
639/// [`MarkdownError::Docx`] when the bytes are not a `.docx` (a `.doc`,
640/// an encrypted document, or RTF is named for what it is rather than
641/// read as a bad ZIP), when the package exceeds the input budget
642/// (`INPUT_LIMIT` for compressed size, entry count, per-part or total
643/// inflation), or when the document cannot be read by
644/// `from_docx` (an OPC read failure, a malformed part, or a missing
645/// main document part).
646///
647/// ```
648/// use jubarte_markdown::markdown::{DocxOptions, MarkdownOptions, docx_to_markdown, markdown_to_docx};
649///
650/// let docx = markdown_to_docx("Due in {~~30~>45~~} days.", &DocxOptions::default())?.docx;
651/// let read = docx_to_markdown(&docx, &MarkdownOptions::default())?;
652/// assert!(read.markdown.starts_with("Due in {~~30~>45~~}"), "{}", read.markdown);
653/// # Ok::<(), jubarte_markdown::markdown::MarkdownError>(())
654/// ```
655pub fn docx_to_markdown(docx: &[u8], options: &MarkdownOptions) -> Result<ReadDocx, MarkdownError> {
656    read_docx(docx, options, false)
657}
658
659/// [`docx_to_markdown`] that also prints each header and footer, between
660/// the body and the notes. A patch reads a change there; a public read does not.
661#[doc(hidden)]
662pub fn docx_to_markdown_stories(
663    docx: &[u8],
664    options: &MarkdownOptions,
665) -> Result<ReadDocx, MarkdownError> {
666    read_docx(docx, options, true)
667}
668
669fn read_docx(
670    docx: &[u8],
671    options: &MarkdownOptions,
672    stories: bool,
673) -> Result<ReadDocx, MarkdownError> {
674    bounded_open(docx, options.input_limits)?;
675    let revisions = match options.track_changes {
676        TrackChanges::All => from_docx::Revisions::Markup,
677        TrackChanges::Accept => from_docx::Revisions::Accept,
678        TrackChanges::Reject => from_docx::Revisions::Reject,
679    };
680    let converted = from_docx::convert(
681        docx,
682        &from_docx::Options {
683            input_limits: options.input_limits,
684            revisions,
685            media_dir: options.extract_media.clone(),
686            ids: options.ids,
687            comments: options.comments,
688            source: options.source.clone(),
689            pages: options.pages.clone(),
690            page_markers: options.page_markers,
691            dates: options.dates,
692            select: options.select.clone(),
693            stories,
694        },
695    )
696    .map_err(|error| MarkdownError::Docx(error.to_string()))?;
697    Ok(ReadDocx {
698        markdown: converted.markdown,
699        media: converted.media.into_iter().collect(),
700        selected: converted.selected,
701        selected_stories: converted.selected_stories,
702    })
703}
704
705/// Refuse `docx` unless it is a package inside `limits`: the sniff, then the
706/// bounded OPC open (entries, sizes, the XML element budget, no DOCTYPE).
707/// Full admission also checks all XML syntax; the view intentionally
708/// tolerates parts it can skip (such as a broken styles part), so the
709/// bounded constructor is used instead.
710fn bounded_open(docx: &[u8], limits: crate::admission::InputLimits) -> Result<(), MarkdownError> {
711    // A `.doc`, an encrypted document or RTF is named for what it is
712    // (`LEGACY_DOC`, `UNSUPPORTED_PACKAGE`), not reported as a bad ZIP.
713    crate::admission::sniff(docx).map_err(|refused| MarkdownError::Docx(refused.to_string()))?;
714    crate::opc::PartFs::open_within(docx, limits)
715        .map(drop)
716        .map_err(|refused| MarkdownError::Docx(crate::opc::refusal_message(docx, &refused)))
717}
718
719/// How [`read`] (and `jubarte read`) prints the agent view. Defaults
720/// to all tracked changes as CriticMarkup, comments inline, no inline
721/// timestamps on notes, `<!-- page N of M -->` lines from the layout
722/// pass, no selection, and no source name.
723#[derive(Clone, Debug, PartialEq, Eq)]
724pub struct ReadOptions {
725    /// Keep the changes as CriticMarkup (`All`), or print the document
726    /// after Word's Accept All or Reject All with `rev` clauses.
727    pub track_changes: TrackChanges,
728    /// Comments inline (`true`), or hidden with their ids on the id lines.
729    pub comments: bool,
730    /// Timestamps inline on the notes of an author with several.
731    /// An author with undated marks always gets explicit dated notes.
732    pub dates: bool,
733    /// `<!-- page N of M -->` lines from the layout pass (`true`), or none.
734    pub page_markers: bool,
735    /// Which blocks of the body to print.
736    pub select: Option<Select>,
737    /// The name printed as `source:` in the header.
738    pub source: Option<String>,
739}
740
741impl Default for ReadOptions {
742    fn default() -> Self {
743        Self {
744            track_changes: TrackChanges::All,
745            comments: true,
746            dates: false,
747            page_markers: true,
748            select: None,
749            source: None,
750        }
751    }
752}
753
754/// A document's agent view and what [`read`] could not show (always
755/// populated, even empty).
756#[derive(Clone, Debug, Default, PartialEq, Eq)]
757pub struct ReadView {
758    /// The YAML header and the Markdown with id lines.
759    pub markdown: String,
760    /// Why the page markers are missing (the layout pass failed) and the
761    /// like. The view is complete otherwise.
762    pub warnings: Vec<String>,
763    /// The body paragraphs [`ReadOptions::select`] kept (`N` of `pN`,
764    /// ascending); `None` without a selection.
765    pub selected: Option<Vec<usize>>,
766    /// The header, footer and note stories (`header1`, `footnotes`) a
767    /// `--changed` selection keeps for their changes; empty otherwise.
768    pub selected_stories: Vec<String>,
769}
770
771/// Reads a `.docx` as the agent view every surface prints for `read`
772/// (alias `text`): a YAML header, then Markdown with an `<!-- pN -->`
773/// id line before every paragraph, tracked changes and comments with
774/// their ids, and `<!-- page N of M -->` markers from the layout pass.
775/// Backs `jubarte read`, `jubarte text`, and the Python / WASM `read`
776/// binding. See `docs/MARKDOWN.md`, "Agent view".
777///
778/// The view is built with [`docx_to_markdown`] and, when `page_markers`
779/// is on, [`page_texts`] feeds [`paginate`] the per-page painted text;
780/// the converter failure (if any) is recorded as a warning and the
781/// markers come from the document's own breaks instead.
782///
783/// # Errors
784///
785/// [`MarkdownError::Docx`] when [`docx_to_markdown`] cannot read the
786/// document.
787///
788/// ```
789/// use jubarte_markdown::markdown::{DocxOptions, ReadOptions, markdown_to_docx, read};
790///
791/// let docx = markdown_to_docx("Due in {~~30~>45~~} days.", &DocxOptions::default())?.docx;
792/// let view = read(&docx, &ReadOptions { page_markers: false, ..ReadOptions::default() })?;
793/// assert!(view.markdown.contains("<!-- p0 -->\nDue in {~~30~>45~~}{r"), "{}", view.markdown);
794/// # Ok::<(), jubarte_markdown::markdown::MarkdownError>(())
795/// ```
796pub fn read(docx: &[u8], options: &ReadOptions) -> Result<ReadView, MarkdownError> {
797    // The view's own budget comes first: the layout pass below admits under
798    // the comparer's larger one, so without this a package `read` refuses
799    // was inflated and laid out before the refusal (4.4 GB for the 215 KB
800    // 70 MiB flood E4 of word_exp, 2026-10-31, #2013).
801    let limits = MarkdownOptions::default().input_limits;
802    bounded_open(docx, limits)?;
803    // Only the layout pass below warns.
804    #[cfg(feature = "render")]
805    let mut warnings = Vec::new();
806    #[cfg(not(feature = "render"))]
807    let warnings = Vec::new();
808    #[cfg(feature = "render")]
809    let pages = if options.page_markers {
810        page_texts(
811            docx,
812            options.track_changes,
813            jubarte_render::convert::RevisionStyle::default(),
814        )
815        // The converter still marks pages, from the document's own breaks.
816        .map_err(|e| {
817            let e = e.to_string();
818            warnings.push(format!(
819                "layout failed, page markers come from the document's breaks: {}",
820                e.strip_prefix("layout failed: ").unwrap_or(&e)
821            ));
822        })
823        .ok()
824    } else {
825        None
826    };
827    #[cfg(not(feature = "render"))]
828    let pages: Option<Vec<String>> = None;
829    let read = docx_to_markdown(
830        docx,
831        &MarkdownOptions {
832            track_changes: options.track_changes,
833            extract_media: None,
834            ids: true,
835            comments: options.comments,
836            source: options.source.clone(),
837            pages,
838            page_markers: options.page_markers,
839            dates: options.dates,
840            select: options.select.clone(),
841            ..MarkdownOptions::default()
842        },
843    )?;
844    Ok(ReadView {
845        markdown: read.markdown,
846        warnings,
847        selected: read.selected,
848        selected_stories: read.selected_stories,
849    })
850}
851
852/// The snapshot `read --json` prints: [`crate::inspect::snapshot`], kept to
853/// the body paragraphs `options.select` picks (and the changes and comments
854/// in them, and under `--changed` those of the stories it changed) when it
855/// picks some. The selection reads the view `options`
856/// describes, without page markers. The view prints a table whole, but a
857/// paragraph pick keeps only the paragraphs it names: `-p p5` of a cell
858/// is p5, not its table; `-p t0` keeps the table's every paragraph.
859/// `options.track_changes` `Accept` or `Reject` reads the text with every
860/// change settled ([`crate::inspect::settled_snapshot`]); `All` is the
861/// plain snapshot. The comments, dates and page-marker options shape only
862/// the view and change nothing here.
863pub fn read_snapshot(
864    docx: &[u8],
865    options: &ReadOptions,
866) -> Result<crate::inspect::Snapshot, MarkdownError> {
867    use crate::inspect::Settle;
868    let docx_error = |e: crate::inspect::InspectError| MarkdownError::Docx(e.to_string());
869    let mut snapshot = match options.track_changes {
870        TrackChanges::All => crate::inspect::snapshot(docx),
871        TrackChanges::Accept => crate::inspect::settled_snapshot(docx, Settle::Accept),
872        TrackChanges::Reject => crate::inspect::settled_snapshot(docx, Settle::Reject),
873    }
874    .map_err(docx_error)?;
875    if options.select.is_some() {
876        let view = read(
877            docx,
878            &ReadOptions {
879                page_markers: false,
880                ..options.clone()
881            },
882        )?;
883        let mut kept = view.selected.unwrap_or_default();
884        if let Some(Select::Picks(picks)) = &options.select {
885            let tables: Vec<Pick> = picks
886                .iter()
887                .filter(|p| matches!(p, Pick::Table(_)))
888                .cloned()
889                .collect();
890            let in_tables = if tables.is_empty() {
891                Vec::new()
892            } else {
893                read(
894                    docx,
895                    &ReadOptions {
896                        page_markers: false,
897                        select: Some(Select::Picks(tables)),
898                        ..options.clone()
899                    },
900                )?
901                .selected
902                .unwrap_or_default()
903            };
904            let named = |n: usize| {
905                picks.iter().any(|p| match p {
906                    Pick::Paragraphs { from, to } => n >= *from && to.is_none_or(|to| n <= to),
907                    Pick::Table(_) => false,
908                })
909            };
910            kept.retain(|&n| named(n) || in_tables.contains(&n));
911        }
912        snapshot.retain_with(&kept, &view.selected_stories);
913    }
914    Ok(snapshot)
915}
916
917/// Why `read --tables` printed nothing.
918#[derive(Debug)]
919pub enum TablesError {
920    /// The selection reaches no table (`p0`, outside every table), or is
921    /// no `-p` pick: a usage error.
922    Usage(String),
923    /// The document cannot be read, or the view refuses the selection as
924    /// `read -p` does (`t5 is not a table of this document`).
925    Read(MarkdownError),
926}
927
928impl std::fmt::Display for TablesError {
929    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
930        match self {
931            Self::Usage(message) => f.write_str(message),
932            Self::Read(error) => error.fmt(f),
933        }
934    }
935}
936
937impl std::error::Error for TablesError {}
938
939/// What `read --tables` prints ([`crate::inspect::tables_text`]): every
940/// body table as a grid, under `options.track_changes` `Reject` with every
941/// change rejected (`Accept` and `All` read the accepted text). With
942/// `options.select` (`-p`), read as the view reads it (`tN` a table
943/// outside every cell, a `pN` or a range the tables that hold it): the
944/// grids of the tables it reaches, each with the tables nested in it, in
945/// document order and once, then an empty line and the view [`read`]
946/// prints of the same selection, unchanged, its warnings with it (#1161).
947/// Without a selection the view's other options change nothing.
948///
949/// # Errors
950///
951/// [`TablesError::Read`] when the document cannot be read or the view
952/// refuses the selection; [`TablesError::Usage`] when a pick reaches no
953/// table or the selection is not `-p`.
954pub fn read_tables(docx: &[u8], options: &ReadOptions) -> Result<ReadView, TablesError> {
955    let read_error =
956        |e: crate::inspect::InspectError| TablesError::Read(MarkdownError::Docx(e.to_string()));
957    let settle =
958        (options.track_changes == TrackChanges::Reject).then_some(crate::inspect::Settle::Reject);
959    let tables = crate::inspect::view_tables(docx, settle).map_err(read_error)?;
960    let Some(select) = &options.select else {
961        let tables: Vec<crate::inspect::Table> =
962            tables.into_iter().map(|(_, table)| table).collect();
963        return Ok(ReadView {
964            markdown: crate::inspect::tables_text(&tables),
965            warnings: Vec::new(),
966            selected: None,
967            selected_stories: Vec::new(),
968        });
969    };
970    let Select::Picks(picks) = select else {
971        return Err(TablesError::Usage(
972            "--tables takes -p only: tN, or a pN inside a table".to_string(),
973        ));
974    };
975    // The view reads the selection first: what it refuses, `read -p`
976    // refuses alike.
977    let view = read(docx, options).map_err(TablesError::Read)?;
978    // The view's table that holds each paragraph (`pN` of a cell, or of a
979    // table nested in one, at any depth).
980    fn own(
981        rows: &[Vec<crate::inspect::TableCell>],
982        nested: &[crate::inspect::NestedTable],
983        number: usize,
984        owner: &mut std::collections::BTreeMap<usize, usize>,
985    ) {
986        for id in rows.iter().flatten().flat_map(|cell| &cell.paragraph_ids) {
987            if let Some(("body", n)) = crate::ids::paragraph_place(id)
988                .as_ref()
989                .map(|(story, n)| (story.as_str(), *n))
990            {
991                owner.insert(n, number);
992            }
993        }
994        for child in nested {
995            own(&child.rows, &child.nested, number, owner);
996        }
997    }
998    let mut owner = std::collections::BTreeMap::new();
999    for (number, table) in &tables {
1000        own(&table.rows, &table.nested, *number, &mut owner);
1001    }
1002    let mut reached = std::collections::BTreeSet::new();
1003    for pick in picks {
1004        match *pick {
1005            Pick::Table(t) => {
1006                reached.insert(t);
1007            }
1008            Pick::Paragraphs { from, to } => {
1009                let mut hit = false;
1010                for (_, &number) in owner.range(from..=to.unwrap_or(usize::MAX)) {
1011                    hit = true;
1012                    reached.insert(number);
1013                }
1014                if !hit {
1015                    let spelled = match to {
1016                        Some(to) if to == from => format!("p{from}"),
1017                        Some(to) => format!("p{from}-p{to}"),
1018                        None => format!("p{from}-"),
1019                    };
1020                    return Err(TablesError::Usage(format!(
1021                        "{spelled} is not in a table; --tables -p takes tN, or a pN inside a table"
1022                    )));
1023                }
1024            }
1025        }
1026    }
1027    let kept: Vec<crate::inspect::Table> = tables
1028        .into_iter()
1029        .filter(|(number, _)| reached.contains(number))
1030        .map(|(_, table)| table)
1031        .collect();
1032    Ok(ReadView {
1033        markdown: format!("{}\n{}", crate::inspect::tables_text(&kept), view.markdown),
1034        ..view
1035    })
1036}
1037
1038/// The view `jubarte edit` and `jubarte add` print after applying:
1039/// the blocks of `docx` (the redline, or with `accepted` its accepted
1040/// text with `rev` tags on the id lines) that carry `author`'s marks,
1041/// as the agent view without page markers. When none does, as after
1042/// resolving another author's comment, the blocks changed by anyone.
1043///
1044/// # Inputs
1045///
1046/// - `docx` — the document to read.
1047/// - `author` — the author whose marks select the blocks.
1048/// - `accepted` — `false` keeps the tracked changes as CriticMarkup;
1049///   `true` reads the accepted text with `rev` clauses on the id
1050///   lines.
1051/// - `source` — the `source:` line written into the header; `None`
1052///   leaves it as `(bytes)`.
1053///
1054/// # Errors
1055///
1056/// [`MarkdownError::Docx`] when [`docx_to_markdown`] cannot read the
1057/// document.
1058pub fn changed_view(
1059    docx: &[u8],
1060    author: &str,
1061    accepted: bool,
1062    source: Option<&str>,
1063) -> Result<String, MarkdownError> {
1064    let options = |by: Option<String>| MarkdownOptions {
1065        track_changes: if accepted {
1066            TrackChanges::Accept
1067        } else {
1068            TrackChanges::All
1069        },
1070        ids: true,
1071        source: source.map(str::to_string),
1072        page_markers: false,
1073        select: Some(Select::Changed { by }),
1074        ..MarkdownOptions::default()
1075    };
1076    let view = docx_to_markdown(docx, &options(Some(author.to_string())))?.markdown;
1077    let empty = view
1078        .splitn(3, "---\n")
1079        .nth(2)
1080        .is_none_or(|body| body.trim().is_empty());
1081    if empty {
1082        return Ok(docx_to_markdown(docx, &options(None))?.markdown);
1083    }
1084    Ok(view)
1085}
1086
1087/// The text the layout pass paints on each page, with the document's
1088/// changes kept (`TrackChanges::All`), accepted (`TrackChanges::Accept`)
1089/// or rejected (`TrackChanges::Reject`). What [`paginate`] matches body
1090/// blocks against to place `<!-- page N of M -->` lines, and what [`read`]
1091/// feeds to its markdown converter.
1092///
1093/// # Inputs
1094///
1095/// - `docx` — the document to lay out.
1096/// - `track_changes` — accept or reject its revisions before laying out,
1097///   or keep them.
1098/// - `revisions` — how the layout pass paints revision marks (the
1099///   conventional red/blue/green redline, the Word-style marks, or a
1100///   `RevisionPalette`). The bench suite measures
1101///   against `RevisionStyle::Word`; call sites that compare a `jubarte`
1102///   PDF against a Word one must pass `RevisionStyle::Word`.
1103///
1104/// # Errors
1105///
1106/// An error string when accepting or rejecting every revision fails, or
1107/// the layout pass fails to admit the package, find its main document
1108/// part, or emit its PDF object stream.
1109#[cfg(feature = "render")]
1110pub fn page_texts(
1111    docx: &[u8],
1112    track_changes: TrackChanges,
1113    revisions: jubarte_render::convert::RevisionStyle,
1114) -> Result<Vec<String>, String> {
1115    let resolved = match track_changes {
1116        TrackChanges::All => Ok(std::borrow::Cow::Borrowed(docx)),
1117        TrackChanges::Accept => crate::document_comparer::accept_revisions(docx)
1118            .map(std::borrow::Cow::Owned)
1119            .map_err(|e| format!("accepting the changes failed: {e:?}")),
1120        TrackChanges::Reject => crate::document_comparer::reject_revisions(docx)
1121            .map(std::borrow::Cow::Owned)
1122            .map_err(|e| format!("rejecting the changes failed: {e:?}")),
1123    };
1124    let rendered = resolved.and_then(|bytes| {
1125        jubarte_render::convert::render(
1126            &bytes,
1127            jubarte_render::convert::PdfOptions {
1128                revisions,
1129                ..jubarte_render::convert::PdfOptions::default()
1130            },
1131            jubarte_render::convert::RenderRequest::default(),
1132        )
1133        .map_err(|e| format!("layout failed: {e}"))
1134    });
1135    rendered.map(|rendered| rendered.report.pages.into_iter().map(|p| p.text).collect())
1136}
1137
1138/// `markdown` (read from `docx`) with `<!-- page N of M -->` lines, as
1139/// `convert --to md` writes it: `docx` is laid out as its PDF would be,
1140/// with its changes kept, accepted or rejected as the Markdown has them,
1141/// and each block found on its page. When layout fails, the Markdown alone
1142/// and why.
1143#[cfg(feature = "render")]
1144#[must_use]
1145pub fn with_page_markers(
1146    docx: &[u8],
1147    markdown: &str,
1148    track_changes: TrackChanges,
1149    revisions: jubarte_render::convert::RevisionStyle,
1150) -> (String, Option<String>) {
1151    match page_texts(docx, track_changes, revisions) {
1152        Ok(pages) => {
1153            let pages: Vec<&str> = pages.iter().map(String::as_str).collect();
1154            (paginate(markdown, &pages), None)
1155        }
1156        Err(e) => (markdown.to_string(), Some(format!("no page markers: {e}"))),
1157    }
1158}
1159
1160/// A written document and what could not be written as asked.
1161#[derive(Clone, Debug, PartialEq, Eq)]
1162pub struct WrittenDocx {
1163    /// The `.docx` bytes.
1164    pub docx: Vec<u8>,
1165    /// Images written as alt text, and the like.
1166    pub warnings: Vec<String>,
1167}
1168
1169/// Why a Markdown / `.docx` document could not be read or written. The
1170/// variants name which side failed: the reference document the caller
1171/// gave, the assembled package, or the document the caller asked to
1172/// read.
1173#[derive(Debug)]
1174pub enum MarkdownError {
1175    /// The reference document is not a readable `.docx`.
1176    Reference(String),
1177    /// The package could not be assembled or accepted/rejected.
1178    Package(String),
1179    /// The document to read is not a readable `.docx`.
1180    Docx(String),
1181}
1182
1183impl std::fmt::Display for MarkdownError {
1184    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1185        match self {
1186            Self::Reference(message) => write!(f, "reference document: {message}"),
1187            Self::Package(message) => write!(f, "cannot write the document: {message}"),
1188            Self::Docx(message) => write!(f, "cannot read the document: {message}"),
1189        }
1190    }
1191}
1192
1193impl std::error::Error for MarkdownError {}
1194
1195#[cfg(test)]
1196#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1197mod tests {
1198    use super::*;
1199
1200    #[test]
1201    fn track_changes_takes_pandocs_values() {
1202        assert_eq!(TrackChanges::parse("all"), Some(TrackChanges::All));
1203        assert_eq!(TrackChanges::parse("accept"), Some(TrackChanges::Accept));
1204        assert_eq!(TrackChanges::parse("reject"), Some(TrackChanges::Reject));
1205        assert_eq!(TrackChanges::parse("markup"), None);
1206        assert_eq!(TrackChanges::default(), TrackChanges::All);
1207    }
1208
1209    #[test]
1210    fn the_bindings_options_read_from_json() {
1211        let reference = [1u8, 2];
1212        let options = docx_options_from_json(
1213            r#"{"page": "a4", "author": "Legal", "date": "2026-10-02T00:00:00Z",
1214               "critic": false, "track_changes": "accept", "tracking": true,
1215               "scholar": true}"#,
1216            Some(&reference),
1217        )
1218        .unwrap();
1219        assert_eq!(options.page, PageSize::A4);
1220        assert_eq!(
1221            (options.author.as_str(), options.author_fixed),
1222            ("Legal", true)
1223        );
1224        assert_eq!(
1225            (options.date.as_str(), options.date_fixed),
1226            ("2026-10-02T00:00:00Z", true)
1227        );
1228        assert!(!options.critic);
1229        assert_eq!(options.track_changes, TrackChanges::Accept);
1230        assert_eq!(options.tracking, Some(true));
1231        assert!(options.scholar);
1232        assert_eq!(options.reference, Some(&reference[..]));
1233        // `trackChanges` is the JavaScript spelling.
1234        let options = docx_options_from_json(r#"{"trackChanges": "reject"}"#, None).unwrap();
1235        assert_eq!(options.track_changes, TrackChanges::Reject);
1236        // Nothing given: the defaults.
1237        let options = docx_options_from_json("{}", None).unwrap();
1238        assert!(options.critic && !options.scholar && !options.author_fixed);
1239        assert_eq!(options.tracking, None);
1240        for (json, word) in [
1241            (r#"{"track_changes": "keep"}"#, "keep"),
1242            (r#"{"page": "legal"}"#, "legal"),
1243            (r#"{"scholarly": true}"#, "scholarly"),
1244        ] {
1245            let error = docx_options_from_json(json, None).unwrap_err();
1246            assert!(error.contains(word), "{error}");
1247        }
1248    }
1249
1250    #[test]
1251    fn resolve_critic_all_is_the_markdown_as_it_is() {
1252        let text = "a {++b++} c";
1253        assert_eq!(resolve_critic(text, TrackChanges::All), text);
1254    }
1255
1256    #[test]
1257    fn errors_and_options_describe_themselves() {
1258        assert_eq!(
1259            MarkdownError::Reference("not a zip".into()).to_string(),
1260            "reference document: not a zip"
1261        );
1262        assert_eq!(
1263            MarkdownError::Package("full".into()).to_string(),
1264            "cannot write the document: full"
1265        );
1266        let loader = |_: &str| None;
1267        let reference = [0u8; 3];
1268        let options = DocxOptions {
1269            reference: Some(&reference),
1270            images: Some(&loader),
1271            ..DocxOptions::default()
1272        };
1273        let debug = format!("{options:?}");
1274        assert!(
1275            debug.contains("reference: Some(3)") && debug.contains("images: true"),
1276            "{debug}"
1277        );
1278        // RedlineOptions' Debug shape is the edit layer's contract; its
1279        // test moved with redline.rs (tests stay beside the behavior).
1280    }
1281}
1282
1283#[cfg(test)]
1284#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1285mod corpus {
1286    use super::*;
1287
1288    pub(crate) fn fixtures(ext: &str) -> Vec<(String, Vec<u8>)> {
1289        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures");
1290        let mut out = Vec::new();
1291        let mut stack = vec![root.clone()];
1292        while let Some(dir) = stack.pop() {
1293            for entry in std::fs::read_dir(&dir).unwrap() {
1294                let path = entry.unwrap().path();
1295                if path.is_dir() {
1296                    stack.push(path);
1297                } else if path.extension().is_some_and(|e| e == ext) {
1298                    // `/`-separated on every platform, so the skip lists
1299                    // below match on Windows too.
1300                    let name = path
1301                        .strip_prefix(&root)
1302                        .unwrap()
1303                        .components()
1304                        .map(|c| c.as_os_str().to_string_lossy())
1305                        .collect::<Vec<_>>()
1306                        .join("/");
1307                    out.push((name, std::fs::read(&path).unwrap()));
1308                }
1309            }
1310        }
1311        out.sort();
1312        out
1313    }
1314
1315    /// Round trips that fail today for reasons reported separately: the
1316    /// Strict text boxes write an ill-formed `document.xml`, and the f4
1317    /// redline writes deleted field parts that validate flags. Skipped,
1318    /// not pinned.
1319    const REPORTED: [&str; 2] = ["strict/Strict01.docx", "f4/word-redline.docx"];
1320
1321    /// Fixtures whose `diff_markdown` of the rejected and accepted views
1322    /// does not resolve back to both views (rows left as `|-|` or `|||`,
1323    /// a stray `{++` after a line break): reported separately, skipped.
1324    const DIFF_REPORTED: [&str; 15] = [
1325        "1676-word.docx",
1326        "1678-word.docx",
1327        "1683-case2-word.docx",
1328        "1686-word-compare.docx",
1329        "f1/word-redline.docx",
1330        "f4/word-redline.docx",
1331        "from-docx/critic/synthetic/all.docx",
1332        "from-docx/critic/synthetic/breaks.docx",
1333        "from-docx/critic/synthetic/hard-delimiters.docx",
1334        "from-docx/critic/synthetic/hard-tables.docx",
1335        "from-docx/critic/synthetic/hard-unicode.docx",
1336        "from-docx/critic/synthetic/structure.docx",
1337        "md-roundtrip/edges/edge-clauses-more.docx",
1338        "md-roundtrip/review/B-row.docx",
1339        "word_probes/final_marks/table_end_word_redline.docx",
1340    ];
1341
1342    fn critic() -> DocxOptions<'static> {
1343        DocxOptions {
1344            critic: true,
1345            ..DocxOptions::default()
1346        }
1347    }
1348
1349    /// Every view of every fixture in shard `k` of 4: the accepted and
1350    /// rejected views carry no CriticMarkup, the full view writes back to
1351    /// a package with no validity finding, and a second round trip is a
1352    /// fixed point.
1353    fn round_trips(k: usize) {
1354        for (i, (name, bytes)) in fixtures("docx").into_iter().enumerate() {
1355            if i % 4 != k {
1356                continue;
1357            }
1358            let read = |options: MarkdownOptions| {
1359                docx_to_markdown(&bytes, &options)
1360                    .unwrap_or_else(|e| panic!("{name}: {e}"))
1361                    .markdown
1362            };
1363            let [accepted, rejected] =
1364                [TrackChanges::Accept, TrackChanges::Reject].map(|track_changes| {
1365                    let md = read(MarkdownOptions {
1366                        track_changes,
1367                        dates: true,
1368                        ..MarkdownOptions::default()
1369                    });
1370                    assert!(
1371                        !["{++", "{--", "{~~"].iter().any(|m| md.contains(m)),
1372                        "{name} {track_changes:?}"
1373                    );
1374                    md
1375                });
1376            // The diff of the two views resolves back to each side.
1377            if !DIFF_REPORTED.contains(&name.as_str()) {
1378                let diff = diff_markdown(&rejected, &accepted);
1379                assert_eq!(
1380                    resolve_critic(&diff, TrackChanges::Accept),
1381                    accepted,
1382                    "{name}"
1383                );
1384                assert_eq!(
1385                    resolve_critic(&diff, TrackChanges::Reject),
1386                    rejected,
1387                    "{name}"
1388                );
1389            }
1390            // The accepted view writes a package Word opens.
1391            let clean = markdown_to_docx(&accepted, &DocxOptions::default()).unwrap();
1392            let fatal = crate::validate::validate(&clean.docx)
1393                .map(|f| f.into_iter().filter(|f| f.word_fatal).count());
1394            assert!(
1395                REPORTED.contains(&name.as_str()) || fatal == Ok(0),
1396                "{name}: {fatal:?}"
1397            );
1398            let agent = read(MarkdownOptions {
1399                ids: true,
1400                comments: true,
1401                ..MarkdownOptions::default()
1402            });
1403            assert!(
1404                agent.contains("<!-- p") || !agent.contains("\n\n"),
1405                "{name}"
1406            );
1407            // The agent view, ids and all, writes back too.
1408            let from_agent =
1409                markdown_to_docx(&agent, &critic()).unwrap_or_else(|e| panic!("{name}: {e}"));
1410            let fatal = crate::validate::validate(&from_agent.docx)
1411                .map(|f| f.into_iter().filter(|f| f.word_fatal).count());
1412            assert!(
1413                REPORTED.contains(&name.as_str()) || fatal == Ok(0),
1414                "{name}: {fatal:?}"
1415            );
1416            // Head, tail and picks read no more than the whole view (and
1417            // its header).
1418            let view = |select: Option<Select>| {
1419                let options = ReadOptions {
1420                    page_markers: false,
1421                    dates: true,
1422                    select,
1423                    ..ReadOptions::default()
1424                };
1425                super::read(&bytes, &options).map(|v| v.markdown.len())
1426            };
1427            let whole = view(None).unwrap_or_else(|e| panic!("{name}: {e}"));
1428            for select in [
1429                Select::Head(2),
1430                Select::Tail(2),
1431                Select::Picks(vec![
1432                    Pick::Paragraphs {
1433                        from: 1,
1434                        to: Some(2),
1435                    },
1436                    Pick::Table(0),
1437                ]),
1438            ] {
1439                if let Ok(len) = view(Some(select.clone())) {
1440                    assert!(len <= whole + 200, "{name} {select:?}: {len} > {whole}");
1441                }
1442            }
1443            // A document with changes has a changed-only view.
1444            let changed = view(Some(Select::Changed { by: None }));
1445            assert!(
1446                accepted == rejected || changed.is_ok(),
1447                "{name}: {changed:?}"
1448            );
1449            docx_to_markdown_stories(&bytes, &MarkdownOptions::default())
1450                .unwrap_or_else(|e| panic!("{name}: {e}"));
1451            let all = read(MarkdownOptions::default());
1452            // Resolving the full view leaves no change marks either way.
1453            // (Strict01's 1.26 MB view takes four minutes to resolve:
1454            // reported, skipped.)
1455            if !DIFF_REPORTED.contains(&name.as_str()) && !REPORTED.contains(&name.as_str()) {
1456                for resolved in [
1457                    resolve_critic(&all, TrackChanges::Accept),
1458                    resolve_critic(&all, TrackChanges::Reject),
1459                    accepted_clauses(&all),
1460                ] {
1461                    assert!(
1462                        !["{++", "{--", "{~~"].iter().any(|m| resolved.contains(m)),
1463                        "{name}"
1464                    );
1465                }
1466            }
1467            let written =
1468                markdown_to_docx(&all, &critic()).unwrap_or_else(|e| panic!("{name}: {e}"));
1469            if REPORTED.contains(&name.as_str()) {
1470                continue;
1471            }
1472            let findings = crate::validate::validate(&written.docx).unwrap();
1473            assert!(findings.is_empty(), "{name}: {findings:?}");
1474            let again = |docx: &[u8]| {
1475                docx_to_markdown(docx, &MarkdownOptions::default())
1476                    .unwrap()
1477                    .markdown
1478            };
1479            let second = again(&written.docx);
1480            let third = again(&markdown_to_docx(&second, &critic()).unwrap().docx);
1481            assert_eq!(second, third, "{name}");
1482        }
1483    }
1484
1485    #[test]
1486    fn fixtures_round_trip_shard_0() {
1487        round_trips(0);
1488    }
1489
1490    #[test]
1491    fn fixtures_round_trip_shard_1() {
1492        round_trips(1);
1493    }
1494
1495    #[test]
1496    fn fixtures_round_trip_shard_2() {
1497        round_trips(2);
1498    }
1499
1500    #[test]
1501    fn fixtures_round_trip_shard_3() {
1502        round_trips(3);
1503    }
1504
1505    /// Every Markdown fixture writes, with and without CriticMarkup, to a
1506    /// package with no Word-fatal finding (informational ones, such as a
1507    /// deletion nested in a deletion that Word reads faithfully, are kept).
1508    #[test]
1509    fn markdown_fixtures_write_valid_packages() {
1510        for (name, md) in fixtures("md") {
1511            let md = String::from_utf8_lossy(&md);
1512            for options in [DocxOptions::default(), critic()] {
1513                let written =
1514                    markdown_to_docx(&md, &options).unwrap_or_else(|e| panic!("{name}: {e}"));
1515                let findings = crate::validate::validate(&written.docx)
1516                    .unwrap_or_else(|e| panic!("{name}: {e}"));
1517                let fatal: Vec<_> = findings.iter().filter(|f| f.word_fatal).collect();
1518                assert!(fatal.is_empty(), "{name}: {fatal:?}");
1519            }
1520        }
1521    }
1522
1523    /// `docx` with a comment and a processing instruction between every
1524    /// two tags of each XML part.
1525    fn with_noise(docx: &[u8]) -> Vec<u8> {
1526        let mut pkg = crate::opc::PartFs::open(docx).unwrap();
1527        for part in pkg.parts() {
1528            if !(part.ends_with(".xml") || part.ends_with(".rels")) {
1529                continue;
1530            }
1531            let xml = pkg.part_string(&part).unwrap();
1532            pkg.set_part(&part, xml.replace("><", "><!--n--><?jr n?><").into_bytes());
1533        }
1534        pkg.to_zip().unwrap()
1535    }
1536
1537    /// Comments and instructions between tags change no reading.
1538    #[test]
1539    fn noise_between_tags_changes_no_view() {
1540        for (name, bytes) in fixtures("docx").into_iter().step_by(2) {
1541            let noisy = with_noise(&bytes);
1542            for options in [
1543                MarkdownOptions::default(),
1544                MarkdownOptions {
1545                    ids: true,
1546                    comments: true,
1547                    ..MarkdownOptions::default()
1548                },
1549            ] {
1550                // The header's sha256 names the bytes, which differ, and a
1551                // drawing's payload carries its XML verbatim, noise and all.
1552                let read = |b: &[u8]| {
1553                    docx_to_markdown(b, &options).map(|r| {
1554                        r.markdown
1555                            .lines()
1556                            .filter(|l| !l.starts_with("sha256: ") && !l.contains("]: drawing:"))
1557                            .collect::<Vec<_>>()
1558                            .join("\n")
1559                    })
1560                };
1561                assert_eq!(read(&noisy).ok(), read(&bytes).ok(), "{name}");
1562            }
1563        }
1564    }
1565}