Skip to main content

jubarte_doc/
fields.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Refresh the cached results of fields from jubarte's own layout.
6//!
7//! [`update_fields`](crate::fields::update_fields) rebuilds every body `TOC` from the heading paragraphs,
8//! lays the document out once, then writes the results of `PAGEREF`, `REF`,
9//! `NUMPAGES` and `SEQ` fields in the body, headers, footers and notes. The
10//! field codes stay, so Word can refresh them later; `w:updateFields` is
11//! not set.
12//!
13//! Page numbers come from jubarte's layout, which matches Word on most
14//! documents but not all (see `docs/WORD_DIFFERENCES.md`). A field whose
15//! switches this module does not implement keeps its cached result; so does
16//! a `PAGEREF` to a bookmark the layout could not page (a bookmark outside
17//! any paragraph, or one in a header). `PAGE` is never written — its result
18//! differs on every page.
19//!
20//! The error strings Word writes for an unresolvable reference
21//! ([`BOOKMARK_NOT_DEFINED`](crate::fields::BOOKMARK_NOT_DEFINED), [`REFERENCE_NOT_FOUND`](crate::fields::REFERENCE_NOT_FOUND),
22//! [`NO_TOC_ENTRIES`](crate::fields::NO_TOC_ENTRIES)) are the public side of that fallback.
23
24use std::collections::{BTreeSet, HashMap};
25use std::fmt;
26
27use serde::{Deserialize, Serialize};
28
29use crate::inspect::{
30    InspectError, Opened, body_paragraph_nodes, parse_part, project_paragraph,
31    story_paragraph_nodes,
32};
33use crate::namespaces::{MC, W};
34use crate::opc::PartFs;
35use crate::xmllinq::{Dom, NodeId, XNamespace};
36
37/// What Word writes for a `PAGEREF` to a bookmark the document lacks.
38pub const BOOKMARK_NOT_DEFINED: &str = "Error! Bookmark not defined.";
39
40/// What Word writes for a `REF` to a bookmark the document lacks.
41pub const REFERENCE_NOT_FOUND: &str = "Error! Reference source not found.";
42
43/// What Word writes for a `TOC` that finds no heading.
44pub const NO_TOC_ENTRIES: &str = "No table of contents entries found.";
45
46/// One field whose cached result [`update_fields`] rewrote.
47#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
48pub struct FieldUpdate {
49    /// Field type, upper case (`PAGEREF`, `REF`, `NUMPAGES`, `SEQ`, `TOC`).
50    pub kind: String,
51    /// The field code, leading and trailing whitespace stripped.
52    pub code: String,
53    /// The paragraph that holds the field's start (`p3`,
54    /// `footer1`), in the output package's numbering.
55    pub paragraph: String,
56    /// The cached result before this run.
57    pub old: String,
58    /// The cached result that was written.
59    pub new: String,
60}
61
62/// Output of [`update_fields`].
63#[derive(Clone, Debug, PartialEq, Eq)]
64pub struct Updated {
65    /// The package with refreshed field results.
66    pub docx: Vec<u8>,
67    /// Every field whose result was rewritten, in story then document order.
68    pub fields: Vec<FieldUpdate>,
69    /// Pages in jubarte's layout of the package.
70    pub page_count: usize,
71}
72
73/// Why [`update_fields`] failed.
74#[derive(Debug)]
75pub enum FieldError {
76    /// The package could not be opened or read (`InspectError`).
77    Inspect(InspectError),
78    /// The layout pass that pages the document failed.
79    Layout(jubarte_render::convert::ConvertError),
80    /// The package could not be serialized back to bytes.
81    Package(String),
82}
83
84impl fmt::Display for FieldError {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        match self {
87            Self::Inspect(err) => err.fmt(f),
88            Self::Layout(err) => write!(f, "laying out: {err}"),
89            Self::Package(err) => write!(f, "writing DOCX: {err}"),
90        }
91    }
92}
93
94impl std::error::Error for FieldError {}
95
96impl From<InspectError> for FieldError {
97    fn from(err: InspectError) -> Self {
98        Self::Inspect(err)
99    }
100}
101
102/// Refresh `PAGEREF`, `REF`, `NUMPAGES`, `SEQ` and `TOC` cached results in
103/// the body, headers, footers and notes.
104///
105/// Page numbers come from jubarte's own layout; see the module-level
106/// comment for the cases where Word's result and ours diverge.
107///
108/// # Errors
109///
110/// - [`FieldError::Inspect`] when the package cannot be opened or read;
111/// - [`FieldError::Layout`] when the layout pass that backs page numbers
112///   fails (see [`jubarte_render::convert::ConvertError`]);
113/// - [`FieldError::Package`] when the rewritten package cannot be
114///   serialized back to bytes.
115pub fn update_fields(docx: &[u8]) -> Result<Updated, FieldError> {
116    let opened = Opened::open(docx)?;
117    let story_parts = opened.story_parts();
118    let styles_part = opened.related("styles").into_iter().next();
119    let Opened {
120        mut pkg,
121        main,
122        dom,
123        document,
124        body,
125    } = opened;
126    let mut stories = vec![Story {
127        id: "body".into(),
128        part: main.clone(),
129        dom,
130        document,
131        root: body,
132        body: true,
133        changed: false,
134    }];
135    for (id, _, part) in story_parts {
136        let (dom, document, root) = parse_part(&pkg, &part)?;
137        stories.push(Story {
138            id,
139            part,
140            dom,
141            document,
142            root,
143            body: false,
144            changed: false,
145        });
146    }
147
148    for story in &mut stories {
149        story.changed |= split_mark_runs(&mut story.dom, story.root);
150    }
151    let style_names = styles_part
152        .as_deref()
153        .and_then(|part| pkg.part_string(part))
154        .map(|xml| paragraph_style_names(&xml))
155        .unwrap_or_default();
156    let mut updates = Vec::new();
157    let tocs = rebuild_tocs(&mut stories[0], &style_names);
158    let mut wanted_styles: BTreeSet<String> =
159        (1..=tocs.max_level).map(|n| format!("TOC{n}")).collect();
160    if !tocs.rebuilt.is_empty() || has_paragraph_style(&stories[0], "TOCHeading") {
161        wanted_styles.insert("TOCHeading".into());
162    }
163    if let Some(part) = &styles_part {
164        add_missing_styles(&mut pkg, part, &wanted_styles);
165    }
166    write_stories(&mut pkg, &mut stories);
167    let staged = pkg
168        .to_zip()
169        .map_err(|err| FieldError::Package(err.to_string()))?;
170    let facts = jubarte_render::convert::layout_facts(&staged).map_err(FieldError::Layout)?;
171
172    let defined: BTreeSet<String> = stories
173        .iter()
174        .flat_map(|story| bookmark_names(&story.dom, story.root))
175        .collect();
176    let context = Context {
177        facts: &facts,
178        defined: &defined,
179    };
180    for story in &mut stories {
181        let ids = paragraph_ids(story);
182        let fields = collect_fields(&story.dom, story.root);
183        let results = results_for(story, &fields, &context);
184        let mut written = Vec::new();
185        for (index, field) in fields.iter().enumerate() {
186            if field.kind == "TOC" {
187                // Recorded once its entries' page numbers are written.
188                if let Some(old) = tocs.rebuilt.get(&field.begin) {
189                    written.push((
190                        updates.len(),
191                        FieldUpdate {
192                            kind: field.kind.clone(),
193                            code: field.code.trim().to_string(),
194                            paragraph: paragraph_id(story, field.begin, &ids),
195                            old: old.clone(),
196                            new: String::new(),
197                        },
198                        field.clone(),
199                    ));
200                }
201                continue;
202            }
203            let Some(new) = results.get(&index) else {
204                continue;
205            };
206            if inside_rewritten_result(&fields, index, &results) {
207                continue;
208            }
209            let old = result_text(&story.dom, story.root, field);
210            if write_result(&mut story.dom, field, new) {
211                story.changed = true;
212                updates.push(FieldUpdate {
213                    kind: field.kind.clone(),
214                    code: field.code.trim().to_string(),
215                    paragraph: paragraph_id(story, field.begin, &ids),
216                    old,
217                    new: new.clone(),
218                });
219            }
220        }
221        for (at, mut update, field) in written.into_iter().rev() {
222            update.new = result_text(&story.dom, story.root, &field);
223            updates.insert(at, update);
224        }
225    }
226    write_stories(&mut pkg, &mut stories);
227    let docx = pkg
228        .to_zip()
229        .map_err(|err| FieldError::Package(err.to_string()))?;
230    Ok(Updated {
231        docx,
232        fields: updates,
233        page_count: facts.page_count,
234    })
235}
236
237struct Story {
238    id: String,
239    part: String,
240    dom: Dom,
241    document: NodeId,
242    root: NodeId,
243    body: bool,
244    changed: bool,
245}
246
247fn write_stories(pkg: &mut PartFs, stories: &mut [Story]) {
248    for story in stories.iter_mut().filter(|story| story.changed) {
249        let xml = story.dom.serialize_document(story.document);
250        pkg.set_part(&story.part, xml.into_bytes());
251        story.changed = false;
252    }
253}
254
255/// What every result is computed from.
256struct Context<'a> {
257    facts: &'a jubarte_render::convert::LayoutFacts,
258    defined: &'a BTreeSet<String>,
259}
260
261// ── field walking ─────────────────────────────────────────────────────────
262
263/// One field in document order. For a complex field `begin`, `separate` and
264/// `end` are its `w:fldChar` elements; for a `w:fldSimple` all three are the
265/// `w:fldSimple` element itself.
266#[derive(Clone, Debug)]
267struct Field {
268    kind: String,
269    code: String,
270    begin: NodeId,
271    separate: Option<NodeId>,
272    end: NodeId,
273    simple: bool,
274    /// The field whose result holds this one, if any.
275    in_result_of: Option<usize>,
276}
277
278/// Every field under `root` in document order (by start). Content that a
279/// revision deleted and `mc:Fallback` copies are skipped; text boxes keep
280/// their own field nesting. A field left open at the end is dropped.
281fn collect_fields(dom: &Dom, root: NodeId) -> Vec<Field> {
282    let mut fields: Vec<Option<Field>> = Vec::new();
283    // Open complex fields per text-box story, as indices into `fields`.
284    let mut stacks: HashMap<Option<NodeId>, Vec<usize>> = HashMap::new();
285    for node in dom.descendants(root, None) {
286        let Some(name) = dom.name(node) else {
287            continue;
288        };
289        if name.namespace_name() != W::URI {
290            continue;
291        }
292        let local = name.local_name();
293        if !matches!(local, "fldChar" | "instrText" | "fldSimple") || skipped(dom, node) {
294            continue;
295        }
296        let story = dom
297            .ancestors(node, Some(&W::txbx_content()))
298            .into_iter()
299            .next();
300        let stack = stacks.entry(story).or_default();
301        let open = |i: &usize| fields[*i].as_ref();
302        let enclosing = stack
303            .iter()
304            .rev()
305            .find(|i| open(i).is_some_and(|f| f.separate.is_some()))
306            .copied();
307        let top = stack.last().copied();
308        match (local, dom.attribute(node, &W::name("fldCharType"))) {
309            ("instrText", _) => {
310                if let Some(field) = top.and_then(|i| fields[i].as_mut())
311                    && field.separate.is_none()
312                {
313                    field.code.push_str(&dom.value(node));
314                }
315            }
316            ("fldSimple", _) => {
317                let code = dom
318                    .attribute(node, &W::name("instr"))
319                    .unwrap_or_default()
320                    .to_string();
321                fields.push(Some(Field {
322                    kind: field_kind(&code),
323                    code,
324                    begin: node,
325                    separate: Some(node),
326                    end: node,
327                    simple: true,
328                    in_result_of: enclosing,
329                }));
330            }
331            (_, Some("begin")) => {
332                stack.push(fields.len());
333                fields.push(Some(Field {
334                    kind: String::new(),
335                    code: String::new(),
336                    begin: node,
337                    separate: None,
338                    end: node,
339                    simple: false,
340                    in_result_of: enclosing,
341                }));
342            }
343            (_, Some("separate")) => {
344                if let Some(field) = top.and_then(|i| fields[i].as_mut()) {
345                    field.separate = Some(node);
346                }
347            }
348            (_, Some("end")) => {
349                if let Some(field) = stack.pop().and_then(|i| fields[i].as_mut()) {
350                    field.end = node;
351                    field.kind = field_kind(&field.code);
352                }
353            }
354            _ => {}
355        }
356    }
357    for i in stacks.into_values().flatten() {
358        fields[i] = None;
359    }
360    // Dropping unclosed fields shifts indices; remap `in_result_of`.
361    let mut remap = HashMap::new();
362    for (old, field) in fields.iter().enumerate() {
363        if field.is_some() {
364            let new = remap.len();
365            remap.insert(old, new);
366        }
367    }
368    fields
369        .into_iter()
370        .flatten()
371        .map(|mut field| {
372            field.in_result_of = field.in_result_of.and_then(|i| remap.get(&i).copied());
373            field
374        })
375        .collect()
376}
377
378/// Give every `w:fldChar` a run of its own, as Word writes fields: a run
379/// that also holds the code or result (generators write a whole field into
380/// one run) is split in place, each piece keeping the run's properties.
381/// Returns whether anything was split.
382fn split_mark_runs(dom: &mut Dom, root: NodeId) -> bool {
383    let runs: Vec<NodeId> = dom
384        .descendants(root, Some(&W::r()))
385        .into_iter()
386        .filter(|&run| {
387            let content: Vec<NodeId> = dom
388                .elements(run, None)
389                .into_iter()
390                .filter(|&c| !dom.name_is(c, &W::r_pr()))
391                .collect();
392            content.len() > 1 && content.iter().any(|&c| dom.name_is(c, &W::fld_char()))
393        })
394        .collect();
395    for &run in &runs {
396        let rpr = dom.element(run, &W::r_pr());
397        let attributes = dom.attributes(run);
398        let mut groups: Vec<Vec<NodeId>> = Vec::new();
399        let mut open = false;
400        for child in dom.elements(run, None) {
401            if Some(child) == rpr {
402                continue;
403            }
404            if dom.name_is(child, &W::fld_char()) {
405                groups.push(vec![child]);
406                open = false;
407            } else if open {
408                groups.last_mut().expect("open group").push(child);
409            } else {
410                groups.push(vec![child]);
411                open = true;
412            }
413        }
414        for group in groups {
415            let piece = dom.new_element(W::r());
416            for (name, value) in &attributes {
417                dom.set_attribute_value(piece, name, Some(value));
418            }
419            if let Some(rpr) = rpr {
420                let copy = dom.clone_subtree(rpr);
421                dom.add(piece, copy);
422            }
423            for child in group {
424                dom.remove(child);
425                dom.add(piece, child);
426            }
427            dom.add_before_self(run, piece);
428        }
429        dom.remove(run);
430    }
431    !runs.is_empty()
432}
433
434/// Deleted content and fallback copies take no part in field results.
435fn skipped(dom: &Dom, node: NodeId) -> bool {
436    dom.ancestors(node, None).into_iter().any(|a| {
437        dom.name_is(a, &W::del())
438            || dom.name_is(a, &W::move_from())
439            || dom.name_is(a, &MC::name("Fallback"))
440    })
441}
442
443/// The field type: the code's first word, upper case.
444fn field_kind(code: &str) -> String {
445    code.split_whitespace()
446        .next()
447        .unwrap_or_default()
448        .to_ascii_uppercase()
449}
450
451/// A field code split into words; a quoted argument is one word.
452fn code_words(code: &str) -> Vec<String> {
453    let mut words = Vec::new();
454    let mut chars = code.chars().peekable();
455    while let Some(&c) = chars.peek() {
456        if c.is_whitespace() {
457            chars.next();
458            continue;
459        }
460        let mut word = String::new();
461        if c == '"' {
462            chars.next();
463            for c in chars.by_ref() {
464                if c == '"' {
465                    break;
466                }
467                word.push(c);
468            }
469        } else {
470            while let Some(&c) = chars.peek() {
471                if c.is_whitespace() {
472                    break;
473                }
474                word.push(c);
475                chars.next();
476            }
477        }
478        words.push(word);
479    }
480    words
481}
482
483/// A parsed field code: positional arguments and switches with their
484/// argument (`\o "1-3"` gives `("o", Some("1-3"))`).
485#[derive(Debug, Default, PartialEq, Eq)]
486struct Code {
487    args: Vec<String>,
488    switches: Vec<(String, Option<String>)>,
489}
490
491/// Parse `code` (kind word excluded); `with_arg` lists the switches that take
492/// an argument for this field type.
493fn parse_code(code: &str, with_arg: &[&str]) -> Code {
494    let mut parsed = Code::default();
495    let mut words = code_words(code).into_iter().skip(1).peekable();
496    while let Some(word) = words.next() {
497        if let Some(switch) = word.strip_prefix('\\') {
498            let switch = switch.to_ascii_lowercase();
499            let takes = matches!(switch.as_str(), "*" | "#" | "@") || with_arg.contains(&&*switch);
500            let arg = if takes {
501                words.next_if(|w| !w.starts_with('\\'))
502            } else {
503                None
504            };
505            parsed.switches.push((switch, arg));
506        } else {
507            parsed.args.push(word);
508        }
509    }
510    parsed
511}
512
513/// Whether every switch of `code` is in `known` (a `\*` switch passes only
514/// with `MERGEFORMAT`, `CHARFORMAT` or `Arabic`: a text result such as
515/// `REF`'s takes no number format).
516fn only_switches(code: &Code, known: &[&str]) -> bool {
517    code.switches
518        .iter()
519        .all(|(switch, arg)| match switch.as_str() {
520            "*" => arg.as_deref().is_some_and(|format| {
521                ["mergeformat", "charformat", "arabic"]
522                    .contains(&format.to_ascii_lowercase().as_str())
523            }),
524            other => known.contains(&other),
525        })
526}
527
528/// A number format a `\*` switch asks for, among those written here.
529/// Word's result for a number its `\*` format cannot write.
530const UNREPRESENTABLE: &str = "Error! Number cannot be represented in specified format.";
531
532#[derive(Clone, Copy, Debug, PartialEq, Eq)]
533enum NumberFormat {
534    Arabic,
535    /// `roman` (false) or `ROMAN` (true).
536    Roman(bool),
537    /// `alphabetic` (false) or `ALPHABETIC` (true).
538    Alpha(bool),
539}
540
541impl NumberFormat {
542    /// `n` in this format, as Word writes it (probe nf1006, 2026-10-06):
543    /// past `z` the letter repeats (27 "aa", 53 "aaa"), past 3999 the M's
544    /// do (4000 "MMMM"), and zero is a single space in Roman and letters.
545    /// Past 780 in letters or 32767 in Roman numerals Word writes
546    /// `UNREPRESENTABLE` (probes bn1006 and bn1006b).
547    fn write(self, n: u32) -> Option<String> {
548        use crate::numbering::{ALPHA_LABEL_MAX, ROMAN_LABEL_MAX};
549        Some(match self {
550            Self::Arabic => n.to_string(),
551            Self::Roman(_) | Self::Alpha(_) if n == 0 => " ".to_string(),
552            Self::Roman(_) if n > ROMAN_LABEL_MAX => UNREPRESENTABLE.to_string(),
553            Self::Alpha(_) if n > ALPHA_LABEL_MAX => UNREPRESENTABLE.to_string(),
554            Self::Roman(upper) => crate::numbering::roman_label(n, upper),
555            Self::Alpha(upper) => crate::numbering::alpha_label(n, upper),
556        })
557    }
558}
559
560/// The number format `code`'s `\*` switches ask for (the last one wins;
561/// `MERGEFORMAT` and `CHARFORMAT` format nothing), or `None` when one asks
562/// for a format not written here (`Ordinal`, `CardText`, `Hex`, ...). The
563/// switch's first letter picks the case: `Roman` and `ROMAN` are upper,
564/// `roman` and `rOMAN` lower (Word 16 probe nf1006, 2026-10-06).
565fn number_format(code: &Code) -> Option<NumberFormat> {
566    // The last format switch wins (Word 16 probe bn1006: "\* CardText
567    // \* roman" and "\* Bogus \* roman" are both "i"); one we do not
568    // write keeps the cached result.
569    let mut format = Some(NumberFormat::Arabic);
570    for (switch, arg) in &code.switches {
571        if switch != "*" {
572            continue;
573        }
574        let arg = arg.as_deref()?;
575        let upper = arg.starts_with(|c: char| c.is_ascii_uppercase());
576        format = match arg.to_ascii_lowercase().as_str() {
577            "roman" => Some(NumberFormat::Roman(upper)),
578            "alphabetic" => Some(NumberFormat::Alpha(upper)),
579            "arabic" => Some(NumberFormat::Arabic),
580            "mergeformat" | "charformat" => format,
581            _ => None,
582        };
583    }
584    format
585}
586
587/// Whether every switch of `code` other than `\*` is in `known`.
588fn plain_switches(code: &Code, known: &[&str]) -> bool {
589    code.switches
590        .iter()
591        .all(|(switch, _)| switch == "*" || known.contains(&switch.as_str()))
592}
593
594/// A page label in `code`'s number format. A label that is not a plain
595/// number (a section's "iii" or "2-1") is written only unformatted.
596fn format_page(label: &str, code: &Code) -> Option<String> {
597    match number_format(code)? {
598        NumberFormat::Arabic => Some(label.to_string()),
599        format => format.write(label.parse().ok()?),
600    }
601}
602
603// ── results ───────────────────────────────────────────────────────────────
604
605/// The result to write for each field this module refreshes, by index.
606fn results_for(story: &Story, fields: &[Field], context: &Context<'_>) -> HashMap<usize, String> {
607    let mut results = HashMap::new();
608    let mut seq: HashMap<String, Option<u32>> = HashMap::new();
609    for (index, field) in fields.iter().enumerate() {
610        let result = match field.kind.as_str() {
611            "PAGEREF" => pageref(&field.code, context),
612            "REF" => reference(&story.dom, story.root, &field.code, context),
613            "NUMPAGES" => {
614                let code = parse_code(&field.code, &[]);
615                (code.args.is_empty() && plain_switches(&code, &[]))
616                    .then(|| number_format(&code))
617                    .flatten()
618                    .and_then(|format| format.write(context.facts.page_count as u32))
619            }
620            "SEQ" if story.body => sequence(&field.code, &mut seq),
621            _ => None,
622        };
623        if let Some(result) = result {
624            results.insert(index, result);
625        }
626    }
627    results
628}
629
630fn pageref(code: &str, context: &Context<'_>) -> Option<String> {
631    let code = parse_code(code, &[]);
632    let [name] = code.args.as_slice() else {
633        return None;
634    };
635    if !plain_switches(&code, &["h"]) {
636        return None;
637    }
638    if !context.defined.contains(name) {
639        return Some(BOOKMARK_NOT_DEFINED.to_string());
640    }
641    // Defined but not paged (outside any paragraph, or in a header): the
642    // cached result stays.
643    let label = context.facts.bookmark_pages.get(name)?;
644    format_page(label, &code)
645}
646
647fn reference(dom: &Dom, root: NodeId, code: &str, context: &Context<'_>) -> Option<String> {
648    let code = parse_code(code, &["d"]);
649    let [name] = code.args.as_slice() else {
650        return None;
651    };
652    if !only_switches(&code, &["h"]) {
653        return None;
654    }
655    if !context.defined.contains(name) {
656        return Some(REFERENCE_NOT_FOUND.to_string());
657    }
658    bookmark_text(dom, root, name)
659}
660
661/// `SEQ ident [\c | \n | \r N | \h]`. An identifier that meets a switch this
662/// module does not implement (`\s`, a number format) stops being counted:
663/// its later fields keep their cached results.
664fn sequence(code: &str, counters: &mut HashMap<String, Option<u32>>) -> Option<String> {
665    let parsed = parse_code(code, &["r", "s"]);
666    let ident = parsed.args.first()?.clone();
667    let counter = counters.entry(ident).or_insert(Some(0));
668    let format = number_format(&parsed);
669    if parsed.args.len() != 1 || !plain_switches(&parsed, &["c", "n", "r", "h"]) || format.is_none()
670    {
671        *counter = None;
672    }
673    let mut value = (*counter)?;
674    let reset = parsed
675        .switches
676        .iter()
677        .find(|(switch, _)| switch == "r")
678        .map(|(_, arg)| arg.as_deref().and_then(|n| n.parse::<u32>().ok()));
679    match reset {
680        Some(Some(n)) => value = n,
681        Some(None) => {
682            *counter = None;
683            return None;
684        }
685        None if parsed.switches.iter().any(|(switch, _)| switch == "c") => {}
686        None => value += 1,
687    }
688    *counter = Some(value);
689    let hidden = parsed.switches.iter().any(|(switch, _)| switch == "h");
690    if hidden {
691        Some(String::new())
692    } else {
693        format?.write(value)
694    }
695}
696
697/// The text a bookmark spans, when it lies within one paragraph.
698fn bookmark_text(dom: &Dom, root: NodeId, name: &str) -> Option<String> {
699    let start = dom
700        .descendants(root, Some(&W::bookmark_start()))
701        .into_iter()
702        .find(|&b| dom.attribute(b, &W::name("name")) == Some(name))?;
703    let id = dom.attribute(start, &W::id())?.to_string();
704    let mut text = String::new();
705    let mut inside = false;
706    let mut crossed = false;
707    for node in dom.descendants(root, None) {
708        if node == start {
709            inside = true;
710            continue;
711        }
712        if !inside {
713            continue;
714        }
715        if dom.name_is(node, &W::bookmark_end())
716            && dom.attribute(node, &W::id()) == Some(id.as_str())
717        {
718            return Some(text);
719        }
720        if dom.name_is(node, &W::p()) {
721            crossed = true;
722            continue;
723        }
724        let piece = if dom.name_is(node, &W::t()) {
725            dom.value(node)
726        } else if dom.name_is(node, &W::name("tab")) && in_run(dom, node) {
727            "\t".to_string()
728        } else {
729            continue;
730        };
731        if skipped(dom, node) {
732            continue;
733        }
734        if crossed {
735            return None;
736        }
737        text.push_str(&piece);
738    }
739    None
740}
741
742fn in_run(dom: &Dom, node: NodeId) -> bool {
743    dom.parent(node).is_some_and(|p| dom.name_is(p, &W::r()))
744}
745
746fn bookmark_names(dom: &Dom, root: NodeId) -> Vec<String> {
747    dom.descendants(root, Some(&W::bookmark_start()))
748        .into_iter()
749        .filter_map(|b| dom.attribute(b, &W::name("name")).map(str::to_string))
750        .collect()
751}
752
753/// Whether `index`'s field lies in the result of a field that is rewritten
754/// too (the outer rewrite replaces it).
755fn inside_rewritten_result(
756    fields: &[Field],
757    index: usize,
758    results: &HashMap<usize, String>,
759) -> bool {
760    let mut at = fields[index].in_result_of;
761    while let Some(outer) = at {
762        if results.contains_key(&outer) {
763            return true;
764        }
765        at = fields[outer].in_result_of;
766    }
767    false
768}
769
770/// The text of a field's cached result (paragraph breaks as `\n`).
771fn result_text(dom: &Dom, root: NodeId, field: &Field) -> String {
772    if field.simple {
773        return dom
774            .descendants(field.begin, None)
775            .into_iter()
776            .filter_map(|n| text_piece(dom, n))
777            .collect();
778    }
779    let Some(separate) = field.separate else {
780        return String::new();
781    };
782    let mut text = String::new();
783    let mut inside = false;
784    let mut new_paragraph = false;
785    for node in dom.descendants(root, None) {
786        if node == separate {
787            inside = true;
788            continue;
789        }
790        if node == field.end {
791            break;
792        }
793        if !inside {
794            continue;
795        }
796        if dom.name_is(node, &W::p()) {
797            new_paragraph = !text.is_empty();
798        }
799        if let Some(piece) = text_piece(dom, node) {
800            if std::mem::take(&mut new_paragraph) {
801                text.push('\n');
802            }
803            text.push_str(&piece);
804        }
805    }
806    text
807}
808
809fn text_piece(dom: &Dom, node: NodeId) -> Option<String> {
810    if skipped(dom, node) {
811        return None;
812    }
813    if dom.name_is(node, &W::t()) {
814        Some(dom.value(node))
815    } else if dom.name_is(node, &W::name("tab")) && in_run(dom, node) {
816        Some("\t".into())
817    } else {
818        None
819    }
820}
821
822/// Replace a field's result runs by one run holding `text`. Returns false,
823/// leaving the field as it was, when its result spans paragraphs.
824fn write_result(dom: &mut Dom, field: &Field, text: &str) -> bool {
825    if field.simple {
826        let simple = field.begin;
827        let rpr = dom
828            .descendants(simple, Some(&W::r_pr()))
829            .into_iter()
830            .next()
831            .map(|rpr| dom.clone_subtree(rpr));
832        dom.remove_nodes(simple);
833        if !text.is_empty() {
834            let run = result_run(dom, rpr, text);
835            dom.add(simple, run);
836        }
837        return true;
838    }
839    let Some(begin_run) = dom.parent(field.begin) else {
840        return false;
841    };
842    let Some(end_run) = dom.parent(field.end) else {
843        return false;
844    };
845    let separate_run = match field.separate {
846        Some(separate) => match dom.parent(separate) {
847            Some(run) => run,
848            None => return false,
849        },
850        None => {
851            // No result yet: a separate run goes before the end run.
852            if dom.parent(begin_run).is_none() || dom.parent(end_run).is_none() {
853                return false;
854            }
855            let run = dom.new_element(W::r());
856            let separate = dom.new_element(W::fld_char());
857            dom.set_attribute_value(separate, &W::name("fldCharType"), Some("separate"));
858            dom.add(run, separate);
859            dom.add_before_self(end_run, run);
860            run
861        }
862    };
863    let Some(parent) = dom.parent(separate_run) else {
864        return false;
865    };
866    if dom.parent(end_run) != Some(parent) {
867        return false;
868    }
869    let siblings = dom.nodes(parent);
870    let (Some(from), Some(to)) = (
871        siblings.iter().position(|&n| n == separate_run),
872        siblings.iter().position(|&n| n == end_run),
873    ) else {
874        return false;
875    };
876    if from >= to {
877        return false;
878    }
879    let between = &siblings[from + 1..to];
880    let rpr = between
881        .iter()
882        .find(|&&n| dom.name_is(n, &W::r()))
883        .and_then(|&run| dom.element(run, &W::r_pr()))
884        .or_else(|| dom.element(begin_run, &W::r_pr()))
885        .map(|rpr| dom.clone_subtree(rpr));
886    for &node in between {
887        dom.remove(node);
888    }
889    // Result content sharing a run with the separate or end mark.
890    if let Some(separate) = field.separate {
891        for node in dom.nodes_after_self(separate) {
892            dom.remove(node);
893        }
894    }
895    for node in dom.nodes_before_self(field.end) {
896        if !dom.name_is(node, &W::r_pr()) {
897            dom.remove(node);
898        }
899    }
900    if !text.is_empty() {
901        let run = result_run(dom, rpr, text);
902        dom.add_before_self(end_run, run);
903    }
904    true
905}
906
907fn result_run(dom: &mut Dom, rpr: Option<NodeId>, text: &str) -> NodeId {
908    let run = dom.new_element(W::r());
909    if let Some(rpr) = rpr {
910        dom.add(run, rpr);
911    }
912    let t = dom.new_element(W::t());
913    dom.set_attribute_value(t, &XNamespace::xml().name("space"), Some("preserve"));
914    dom.add_text(t, text);
915    dom.add(run, t);
916    run
917}
918
919// ── paragraph ids ─────────────────────────────────────────────────────────
920
921fn paragraph_ids(story: &Story) -> HashMap<NodeId, usize> {
922    let nodes = if story.body {
923        body_paragraph_nodes(&story.dom, story.root)
924    } else {
925        story_paragraph_nodes(&story.dom, story.root)
926    };
927    nodes.into_iter().enumerate().map(|(i, p)| (p, i)).collect()
928}
929
930/// The id ([`crate::ids::paragraph_id`]) of the paragraph that holds `node` (for a text box,
931/// the paragraph that anchors it).
932fn paragraph_id(story: &Story, node: NodeId, ids: &HashMap<NodeId, usize>) -> String {
933    story
934        .dom
935        .ancestors_and_self(node, Some(&W::p()))
936        .into_iter()
937        .find_map(|p| ids.get(&p))
938        .map(|&i| crate::ids::paragraph_id(&story.id, i))
939        .unwrap_or_default()
940}
941
942// ── TOC ───────────────────────────────────────────────────────────────────
943
944#[derive(Default)]
945struct Tocs {
946    /// TOC begin mark to its result text before the rebuild.
947    rebuilt: HashMap<NodeId, String>,
948    /// Deepest entry level written.
949    max_level: u8,
950}
951
952struct Heading {
953    paragraph: NodeId,
954    level: u8,
955    text: String,
956}
957
958/// Rebuild every body `TOC` whose switches this module implements.
959fn rebuild_tocs(story: &mut Story, style_names: &HashMap<String, String>) -> Tocs {
960    let mut tocs = Tocs::default();
961    let fields = collect_fields(&story.dom, story.root);
962    let toc_fields: Vec<Field> = fields
963        .into_iter()
964        .filter(|f| f.kind == "TOC" && !f.simple && f.in_result_of.is_none())
965        .collect();
966    if toc_fields.is_empty() {
967        return tocs;
968    }
969    // Word sets the entries' right tab 10 twips inside the text width
970    // (w:pos="9350" on a 9360-twip Letter text width in the corpus TOCs
971    // behavior__pageref_standalone_uppercase_h and sd_2447_toc_tab_alignment).
972    let width = text_width(&story.dom, story.root) - 10;
973    let mut names = BookmarkNamer::new(&story.dom, story.root);
974    for field in toc_fields {
975        let code = parse_code(
976            &field.code,
977            &["o", "t", "b", "c", "f", "l", "n", "p", "s", "d", "a"],
978        );
979        if !code.args.is_empty() || !only_switches(&code, &["o", "h", "z", "u", "w", "x"]) {
980            continue;
981        }
982        let Some(levels) = toc_levels(&code) else {
983            continue;
984        };
985        let outline = code.switches.iter().any(|(s, _)| s == "u");
986        let hyperlinks = code.switches.iter().any(|(s, _)| s == "h");
987        let old = result_text(&story.dom, story.root, &field);
988        let headings = headings(&story.dom, story.root, style_names, &levels, outline);
989        let entries: Vec<(u8, String, String)> = headings
990            .iter()
991            .map(|h| {
992                let name = names.ensure(&mut story.dom, h.paragraph);
993                (h.level, h.text.clone(), name)
994            })
995            .collect();
996        if write_toc(&mut story.dom, &field, &entries, hyperlinks, width) {
997            tocs.max_level = tocs
998                .max_level
999                .max(entries.iter().map(|e| e.0).max().unwrap_or(0));
1000            tocs.rebuilt.insert(field.begin, old);
1001            story.changed = true;
1002        }
1003    }
1004    tocs
1005}
1006
1007/// `\o "a-b"` levels, 1 to 9 without `\o`.
1008fn toc_levels(code: &Code) -> Option<std::ops::RangeInclusive<u8>> {
1009    let Some((_, arg)) = code.switches.iter().find(|(s, _)| s == "o") else {
1010        return Some(1..=9);
1011    };
1012    let Some(arg) = arg else {
1013        return Some(1..=9);
1014    };
1015    let (from, to) = arg.split_once('-').unwrap_or((arg, arg));
1016    let from: u8 = from.trim().parse().ok()?;
1017    let to: u8 = to.trim().parse().ok()?;
1018    (1 <= from && from <= to && to <= 9).then_some(from..=to)
1019}
1020
1021/// Heading paragraphs in body order: style id `Heading{n}` or style name
1022/// `heading {n}`; with `\u`, also a direct `w:outlineLvl`.
1023fn headings(
1024    dom: &Dom,
1025    body: NodeId,
1026    style_names: &HashMap<String, String>,
1027    levels: &std::ops::RangeInclusive<u8>,
1028    outline: bool,
1029) -> Vec<Heading> {
1030    body_paragraph_nodes(dom, body)
1031        .into_iter()
1032        .filter_map(|p| {
1033            let ppr = dom.element(p, &W::p_pr());
1034            let style = ppr
1035                .and_then(|ppr| dom.element(ppr, &W::p_style()))
1036                .and_then(|s| dom.attribute(s, &W::val()));
1037            let by_style = style.and_then(|id| heading_level(id, style_names));
1038            let by_outline = outline
1039                .then(|| {
1040                    ppr.and_then(|ppr| dom.element(ppr, &W::name("outlineLvl")))
1041                        .and_then(|o| dom.attribute(o, &W::val()))
1042                        .and_then(|v| v.parse::<u8>().ok())
1043                        .filter(|&v| v < 9)
1044                        .map(|v| v + 1)
1045                })
1046                .flatten();
1047            let level = by_outline.or(by_style)?;
1048            if !levels.contains(&level) {
1049                return None;
1050            }
1051            let text = project_paragraph(dom, p)
1052                .text
1053                .replace(['\n', '\t'], " ")
1054                .trim()
1055                .to_string();
1056            (!text.is_empty()).then_some(Heading {
1057                paragraph: p,
1058                level,
1059                text,
1060            })
1061        })
1062        .collect()
1063}
1064
1065fn heading_level(style_id: &str, style_names: &HashMap<String, String>) -> Option<u8> {
1066    let level = |s: &str| s.parse::<u8>().ok().filter(|n| (1..=9).contains(n));
1067    if let Some(n) = style_id.strip_prefix("Heading").and_then(level) {
1068        return Some(n);
1069    }
1070    style_names
1071        .get(style_id)
1072        .and_then(|name| name.strip_prefix("heading "))
1073        .and_then(level)
1074}
1075
1076/// Gives each heading a `_Toc` bookmark inside its paragraph, reusing one it
1077/// already has.
1078struct BookmarkNamer {
1079    taken: BTreeSet<String>,
1080    next_id: u64,
1081    next_name: u64,
1082}
1083
1084impl BookmarkNamer {
1085    fn new(dom: &Dom, root: NodeId) -> Self {
1086        let starts = dom.descendants(root, Some(&W::bookmark_start()));
1087        let next_id = starts
1088            .iter()
1089            .filter_map(|&b| {
1090                dom.attribute(b, &W::id())
1091                    .and_then(|v| v.parse::<u64>().ok())
1092            })
1093            .max()
1094            .map_or(0, |max| max + 1);
1095        Self {
1096            taken: bookmark_names(dom, root).into_iter().collect(),
1097            next_id,
1098            next_name: 100_000_001,
1099        }
1100    }
1101
1102    fn ensure(&mut self, dom: &mut Dom, paragraph: NodeId) -> String {
1103        if let Some(name) = dom
1104            .descendants(paragraph, Some(&W::bookmark_start()))
1105            .into_iter()
1106            .filter_map(|b| dom.attribute(b, &W::name("name")))
1107            .find(|name| name.starts_with("_Toc"))
1108        {
1109            return name.to_string();
1110        }
1111        let name = loop {
1112            let name = format!("_Toc{}", self.next_name);
1113            self.next_name += 1;
1114            if self.taken.insert(name.clone()) {
1115                break name;
1116            }
1117        };
1118        let id = self.next_id.to_string();
1119        self.next_id += 1;
1120        let start = dom.new_element(W::bookmark_start());
1121        dom.set_attribute_value(start, &W::id(), Some(&id));
1122        dom.set_attribute_value(start, &W::name("name"), Some(&name));
1123        let end = dom.new_element(W::bookmark_end());
1124        dom.set_attribute_value(end, &W::id(), Some(&id));
1125        match dom.element(paragraph, &W::p_pr()) {
1126            Some(ppr) => dom.add_after_self(ppr, start),
1127            None => dom.add_first(paragraph, start),
1128        }
1129        dom.add(paragraph, end);
1130        name
1131    }
1132}
1133
1134/// The body text width in twips, from the final section.
1135fn text_width(dom: &Dom, body: NodeId) -> i64 {
1136    let twips = |node: Option<NodeId>, name: &str| {
1137        node.and_then(|n| dom.attribute(n, &W::name(name)))
1138            .and_then(|v| v.parse::<i64>().ok())
1139    };
1140    let sect = dom.element(body, &W::sect_pr());
1141    let size = sect.and_then(|s| dom.element(s, &W::name("pgSz")));
1142    let margins = sect.and_then(|s| dom.element(s, &W::name("pgMar")));
1143    let width = twips(size, "w").unwrap_or(12240)
1144        - twips(margins, "left").unwrap_or(1440)
1145        - twips(margins, "right").unwrap_or(1440)
1146        - twips(margins, "gutter").unwrap_or(0);
1147    width.max(720)
1148}
1149
1150/// Write `entries` as the TOC's result: the first entry in the paragraph that
1151/// holds the field's start, one paragraph per further entry, the end mark in
1152/// the last. Returns false when the field's marks are not where Word puts
1153/// them (each in a run whose parent is a paragraph).
1154fn write_toc(
1155    dom: &mut Dom,
1156    field: &Field,
1157    entries: &[(u8, String, String)],
1158    hyperlinks: bool,
1159    width: i64,
1160) -> bool {
1161    let (Some(begin_run), Some(end_run)) = (dom.parent(field.begin), dom.parent(field.end)) else {
1162        return false;
1163    };
1164    if begin_run == end_run || field.separate.and_then(|s| dom.parent(s)) == Some(end_run) {
1165        return false;
1166    }
1167    let (Some(first), Some(last)) = (dom.parent(begin_run), dom.parent(end_run)) else {
1168        return false;
1169    };
1170    if !dom.name_is(first, &W::p()) || !dom.name_is(last, &W::p()) {
1171        return false;
1172    }
1173    if let Some(separate) = field.separate
1174        && dom.parent(separate).and_then(|run| dom.parent(run)) != Some(first)
1175    {
1176        return false;
1177    }
1178    let separate_run = match field.separate.and_then(|s| dom.parent(s)) {
1179        Some(run) => run,
1180        None => {
1181            // A TOC without a result: the separate mark goes right after the
1182            // last code run.
1183            let code_end = dom
1184                .nodes_after_self(begin_run)
1185                .into_iter()
1186                .take_while(|&n| n != end_run)
1187                .filter(|&n| !dom.descendants(n, Some(&W::instr_text())).is_empty())
1188                .last()
1189                .unwrap_or(begin_run);
1190            let run = fld_char_run(dom, "separate");
1191            dom.add_after_self(code_end, run);
1192            run
1193        }
1194    };
1195    // Drop the old result: siblings after the separate run in the first
1196    // paragraph, whole paragraphs between, siblings before the end run.
1197    if first == last {
1198        let siblings = dom.nodes(first);
1199        let from = siblings.iter().position(|&n| n == separate_run);
1200        let to = siblings.iter().position(|&n| n == end_run);
1201        if let (Some(from), Some(to)) = (from, to)
1202            && from < to
1203        {
1204            for &node in &siblings[from + 1..to] {
1205                dom.remove(node);
1206            }
1207        }
1208    } else {
1209        for node in dom.nodes_after_self(separate_run) {
1210            dom.remove(node);
1211        }
1212        let mut next = dom.next_element(first);
1213        while let Some(node) = next {
1214            if node == last {
1215                break;
1216            }
1217            next = dom.next_element(node);
1218            dom.remove(node);
1219        }
1220        for node in dom.nodes_before_self(end_run) {
1221            if !dom.name_is(node, &W::p_pr()) {
1222                dom.remove(node);
1223            }
1224        }
1225    }
1226
1227    if entries.is_empty() {
1228        let run = result_run(dom, None, NO_TOC_ENTRIES);
1229        dom.add_after_self(separate_run, run);
1230        return true;
1231    }
1232    // Where each entry's runs go: after the separate mark, appended to a
1233    // new paragraph, or (the last entry of a TOC that already ends in its
1234    // own paragraph) before the end mark.
1235    enum At {
1236        After(NodeId),
1237        Append,
1238        Before(NodeId),
1239    }
1240    let mut paragraph = first;
1241    for (i, (level, text, bookmark)) in entries.iter().enumerate() {
1242        let at = if i == 0 {
1243            At::After(separate_run)
1244        } else if first != last && i == entries.len() - 1 {
1245            paragraph = last;
1246            At::Before(end_run)
1247        } else {
1248            let p = dom.new_element(W::p());
1249            dom.add_after_self(paragraph, p);
1250            paragraph = p;
1251            At::Append
1252        };
1253        set_entry_properties(dom, paragraph, *level, width);
1254        let content = entry_content(dom, text, bookmark, hyperlinks);
1255        match at {
1256            At::After(mut after) => {
1257                for node in content {
1258                    dom.add_after_self(after, node);
1259                    after = node;
1260                }
1261            }
1262            At::Append => {
1263                for node in content {
1264                    dom.add(paragraph, node);
1265                }
1266            }
1267            At::Before(end) => {
1268                for node in content {
1269                    dom.add_before_self(end, node);
1270                }
1271            }
1272        }
1273    }
1274    if first == last && paragraph != first {
1275        // The end mark and whatever followed it close the last entry.
1276        let mut moving = vec![end_run];
1277        moving.extend(dom.nodes_after_self(end_run));
1278        for node in moving {
1279            dom.remove(node);
1280            dom.add(paragraph, node);
1281        }
1282    }
1283    true
1284}
1285
1286fn fld_char_run(dom: &mut Dom, kind: &str) -> NodeId {
1287    let run = dom.new_element(W::r());
1288    let mark = dom.new_element(W::fld_char());
1289    dom.set_attribute_value(mark, &W::name("fldCharType"), Some(kind));
1290    dom.add(run, mark);
1291    run
1292}
1293
1294/// `TOC{level}` style and a right tab with a dot leader at the text width.
1295/// The style is set only when the paragraph has none or a TOC style already,
1296/// so a field placed in a styled paragraph keeps it.
1297fn set_entry_properties(dom: &mut Dom, paragraph: NodeId, level: u8, width: i64) {
1298    let ppr = match dom.element(paragraph, &W::p_pr()) {
1299        Some(ppr) => ppr,
1300        None => {
1301            let ppr = dom.new_element(W::p_pr());
1302            dom.add_first(paragraph, ppr);
1303            ppr
1304        }
1305    };
1306    let style = dom.element(ppr, &W::p_style());
1307    let keep = style
1308        .and_then(|s| dom.attribute(s, &W::val()))
1309        .is_some_and(|id| !id.starts_with("TOC"));
1310    if !keep {
1311        let style = style.unwrap_or_else(|| {
1312            let s = dom.new_element(W::p_style());
1313            dom.add_first(ppr, s);
1314            s
1315        });
1316        dom.set_attribute_value(style, &W::val(), Some(&format!("TOC{level}")));
1317    }
1318    if let Some(tabs) = dom.element(ppr, &W::name("tabs")) {
1319        dom.remove(tabs);
1320    }
1321    let tabs = dom.new_element(W::name("tabs"));
1322    let tab = dom.new_element(W::name("tab"));
1323    dom.set_attribute_value(tab, &W::val(), Some("right"));
1324    dom.set_attribute_value(tab, &W::name("leader"), Some("dot"));
1325    dom.set_attribute_value(tab, &W::name("pos"), Some(&width.to_string()));
1326    dom.add(tabs, tab);
1327    // Schema order: pStyle, keepNext, keepLines, pageBreakBefore, framePr,
1328    // widowControl, numPr, suppressLineNumbers, pBdr, shd, tabs, ...
1329    const BEFORE_TABS: [&str; 10] = [
1330        "pStyle",
1331        "keepNext",
1332        "keepLines",
1333        "pageBreakBefore",
1334        "framePr",
1335        "widowControl",
1336        "numPr",
1337        "suppressLineNumbers",
1338        "pBdr",
1339        "shd",
1340    ];
1341    let after = dom
1342        .elements(ppr, None)
1343        .into_iter()
1344        .take_while(|&c| {
1345            dom.name(c)
1346                .is_some_and(|n| BEFORE_TABS.contains(&n.local_name()))
1347        })
1348        .last();
1349    match after {
1350        Some(node) => dom.add_after_self(node, tabs),
1351        None => dom.add_first(ppr, tabs),
1352    }
1353}
1354
1355/// An entry's runs: the heading text, a tab and a `PAGEREF \h` field with an
1356/// empty result, wrapped in a hyperlink to the bookmark when `hyperlinks`.
1357fn entry_content(dom: &mut Dom, text: &str, bookmark: &str, hyperlinks: bool) -> Vec<NodeId> {
1358    let mut runs = vec![result_run(dom, None, text)];
1359    let tab_run = dom.new_element(W::r());
1360    let tab = dom.new_element(W::name("tab"));
1361    dom.add(tab_run, tab);
1362    runs.push(tab_run);
1363    runs.push(fld_char_run(dom, "begin"));
1364    let code_run = dom.new_element(W::r());
1365    let instr = dom.new_element(W::instr_text());
1366    dom.set_attribute_value(instr, &XNamespace::xml().name("space"), Some("preserve"));
1367    dom.add_text(instr, &format!(" PAGEREF {bookmark} \\h "));
1368    dom.add(code_run, instr);
1369    runs.push(code_run);
1370    runs.push(fld_char_run(dom, "separate"));
1371    runs.push(fld_char_run(dom, "end"));
1372    if !hyperlinks {
1373        return runs;
1374    }
1375    let link = dom.new_element(W::hyperlink());
1376    dom.set_attribute_value(link, &W::name("anchor"), Some(bookmark));
1377    dom.set_attribute_value(link, &W::name("history"), Some("1"));
1378    for run in runs {
1379        dom.add(link, run);
1380    }
1381    vec![link]
1382}
1383
1384fn has_paragraph_style(story: &Story, id: &str) -> bool {
1385    story
1386        .dom
1387        .descendants(story.root, Some(&W::p_style()))
1388        .into_iter()
1389        .any(|s| story.dom.attribute(s, &W::val()) == Some(id))
1390}
1391
1392// ── styles ────────────────────────────────────────────────────────────────
1393
1394/// Paragraph style id to its name, lower case.
1395fn paragraph_style_names(styles_xml: &str) -> HashMap<String, String> {
1396    let mut dom = Dom::new();
1397    let document = dom.parse_xdocument(styles_xml);
1398    let Some(root) = dom.root(document) else {
1399        return HashMap::new();
1400    };
1401    dom.elements(root, Some(&W::name("style")))
1402        .into_iter()
1403        .filter(|&s| dom.attribute(s, &W::type_()) == Some("paragraph"))
1404        .filter_map(|s| {
1405            let id = dom.attribute(s, &W::name("styleId"))?.to_string();
1406            let name = dom
1407                .element(s, &W::name("name"))
1408                .and_then(|n| dom.attribute(n, &W::val()))?
1409                .to_ascii_lowercase();
1410            Some((id, name))
1411        })
1412        .collect()
1413}
1414
1415/// Add Word's built-in definition of each wanted TOC style the styles part
1416/// lacks. A package without a styles part is left without one.
1417pub(crate) fn add_missing_styles(pkg: &mut PartFs, part: &str, wanted: &BTreeSet<String>) {
1418    let Some(styles) = pkg.part_string(part) else {
1419        return;
1420    };
1421    let missing: String = wanted
1422        .iter()
1423        .filter(|id| !styles.contains(&format!("w:styleId=\"{id}\"")))
1424        .filter_map(|id| style_definition(id))
1425        .collect();
1426    if missing.is_empty() {
1427        return;
1428    }
1429    if let Some(at) = styles.rfind("</w:styles>") {
1430        let xml = format!("{}{missing}{}", &styles[..at], &styles[at..]);
1431        pkg.set_part(part, xml.into_bytes());
1432    }
1433}
1434
1435/// Word's `toc 1` to `toc 9` and `TOC Heading` definitions.
1436fn style_definition(id: &str) -> Option<String> {
1437    if id == "TOCHeading" {
1438        return Some(
1439            "<w:style w:type=\"paragraph\" w:styleId=\"TOCHeading\"><w:name w:val=\"TOC Heading\"/>\
1440             <w:basedOn w:val=\"Heading1\"/><w:next w:val=\"Normal\"/><w:uiPriority w:val=\"39\"/>\
1441             <w:unhideWhenUsed/><w:qFormat/><w:pPr><w:outlineLvl w:val=\"9\"/></w:pPr></w:style>"
1442                .to_string(),
1443        );
1444    }
1445    let level: u32 = id.strip_prefix("TOC")?.parse().ok()?;
1446    if !(1..=9).contains(&level) {
1447        return None;
1448    }
1449    let indent = (level - 1) * 220;
1450    Some(format!(
1451        "<w:style w:type=\"paragraph\" w:styleId=\"TOC{level}\"><w:name w:val=\"toc {level}\"/>\
1452         <w:basedOn w:val=\"Normal\"/><w:next w:val=\"Normal\"/><w:autoRedefine/>\
1453         <w:uiPriority w:val=\"39\"/><w:unhideWhenUsed/><w:pPr><w:spacing w:after=\"100\"/>\
1454         <w:ind w:left=\"{indent}\"/></w:pPr></w:style>"
1455    ))
1456}
1457
1458#[cfg(test)]
1459#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1460mod tests {
1461    use std::io::{Cursor, Write};
1462
1463    use super::*;
1464
1465    /// The smallest package: content types, package rels, the body.
1466    pub(super) fn tiny_docx(body: &str) -> Vec<u8> {
1467        let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
1468        let opt = zip::write::SimpleFileOptions::default();
1469        let mut put = |name: &str, data: &str| {
1470            zip.start_file(name, opt).unwrap();
1471            zip.write_all(data.as_bytes()).unwrap();
1472        };
1473        put(
1474            "[Content_Types].xml",
1475            r#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#,
1476        );
1477        put(
1478            "_rels/.rels",
1479            r#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#,
1480        );
1481        put(
1482            "word/document.xml",
1483            &format!(
1484                r#"<?xml version="1.0"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}<w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/></w:sectPr></w:body></w:document>"#
1485            ),
1486        );
1487        zip.finish().unwrap().into_inner()
1488    }
1489
1490    /// Spike: the layout pages body bookmarks that sit inside a paragraph.
1491    #[test]
1492    fn layout_facts_page_the_bookmarks_inside_body_paragraphs() {
1493        let body = concat!(
1494            r#"<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:bookmarkStart w:id="1" w:name="_Toc1"/><w:r><w:t>A</w:t></w:r><w:bookmarkEnd w:id="1"/></w:p>"#,
1495            r#"<w:p><w:r><w:br w:type="page"/></w:r></w:p>"#,
1496            r#"<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:bookmarkStart w:id="2" w:name="_Toc2"/><w:r><w:t>B</w:t></w:r><w:bookmarkEnd w:id="2"/></w:p>"#,
1497            r#"<w:bookmarkStart w:id="3" w:name="outside"/><w:bookmarkEnd w:id="3"/>"#,
1498        );
1499        let facts = jubarte_render::convert::layout_facts(&tiny_docx(body)).unwrap();
1500        assert_eq!(facts.page_count, 2);
1501        let pages: Vec<(&str, &str)> = facts
1502            .bookmark_pages
1503            .iter()
1504            .map(|(k, v)| (k.as_str(), v.as_str()))
1505            .collect();
1506        assert_eq!(pages, [("_Toc1", "1"), ("_Toc2", "2")]);
1507    }
1508
1509    #[test]
1510    fn codes_split_into_arguments_and_switches() {
1511        let code = parse_code(r#" TOC \o "1-3" \h \z \u "#, &["o"]);
1512        assert!(code.args.is_empty());
1513        assert_eq!(
1514            code.switches,
1515            [
1516                ("o".to_string(), Some("1-3".to_string())),
1517                ("h".to_string(), None),
1518                ("z".to_string(), None),
1519                ("u".to_string(), None),
1520            ]
1521        );
1522        let code = parse_code(r#" REF  "my mark" \* MERGEFORMAT"#, &[]);
1523        assert_eq!(code.args, ["my mark"]);
1524        assert!(only_switches(&code, &[]));
1525        assert!(!only_switches(&parse_code(" NUMPAGES \\* roman", &[]), &[]));
1526        assert_eq!(field_kind("  pageref x"), "PAGEREF");
1527        assert_eq!(field_kind(""), "");
1528    }
1529
1530    #[test]
1531    fn number_formats_write_roman_and_letters() {
1532        let format = |code: &str| number_format(&parse_code(code, &[]));
1533        assert_eq!(format(" NUMPAGES "), Some(NumberFormat::Arabic));
1534        assert_eq!(
1535            format(" NUMPAGES \\* MERGEFORMAT "),
1536            Some(NumberFormat::Arabic)
1537        );
1538        assert_eq!(
1539            format(" NUMPAGES \\* roman "),
1540            Some(NumberFormat::Roman(false))
1541        );
1542        assert_eq!(
1543            format(" NUMPAGES \\* ROMAN \\* MERGEFORMAT "),
1544            Some(NumberFormat::Roman(true))
1545        );
1546        assert_eq!(
1547            format(" SEQ x \\* alphabetic "),
1548            Some(NumberFormat::Alpha(false))
1549        );
1550        assert_eq!(
1551            format(" SEQ x \\* ALPHABETIC "),
1552            Some(NumberFormat::Alpha(true))
1553        );
1554        // Word 16 probe nf1006 (2026-10-06): the switch's first letter
1555        // picks the case, "Roman" XIV and "rOMAN" xiv.
1556        assert_eq!(
1557            format(" NUMPAGES \\* Roman "),
1558            Some(NumberFormat::Roman(true))
1559        );
1560        assert_eq!(
1561            format(" NUMPAGES \\* rOMAN "),
1562            Some(NumberFormat::Roman(false))
1563        );
1564        assert_eq!(
1565            format(" SEQ x \\* Alphabetic "),
1566            Some(NumberFormat::Alpha(true))
1567        );
1568        assert_eq!(
1569            format(" SEQ x \\* aLPHABETIC "),
1570            Some(NumberFormat::Alpha(false))
1571        );
1572        // Formats not written here keep the cached result.
1573        assert_eq!(format(" NUMPAGES \\* CardText "), None);
1574        assert_eq!(NumberFormat::Roman(false).write(14).as_deref(), Some("xiv"));
1575        assert_eq!(
1576            NumberFormat::Roman(true).write(1999).as_deref(),
1577            Some("MCMXCIX")
1578        );
1579        assert_eq!(NumberFormat::Alpha(false).write(3).as_deref(), Some("c"));
1580        assert_eq!(NumberFormat::Alpha(true).write(26).as_deref(), Some("Z"));
1581        assert_eq!(NumberFormat::Arabic.write(0).as_deref(), Some("0"));
1582        // nf1006: past z the letter repeats, past 3999 the M's do, and
1583        // zero is a single space in both.
1584        assert_eq!(NumberFormat::Alpha(false).write(27).as_deref(), Some("aa"));
1585        assert_eq!(NumberFormat::Alpha(true).write(53).as_deref(), Some("AAA"));
1586        assert_eq!(
1587            NumberFormat::Roman(true).write(4000).as_deref(),
1588            Some("MMMM")
1589        );
1590        assert_eq!(NumberFormat::Roman(false).write(0).as_deref(), Some(" "));
1591        assert_eq!(NumberFormat::Alpha(false).write(0).as_deref(), Some(" "));
1592        // Word 16 probes bn1006 / bn1006b (2026-10-06): letters reach 780
1593        // (thirty z's) and Roman 32767; past them Word writes its error.
1594        assert_eq!(
1595            NumberFormat::Alpha(false).write(780).as_deref(),
1596            Some("z".repeat(30).as_str())
1597        );
1598        for (format, n) in [
1599            (NumberFormat::Alpha(false), 781),
1600            (NumberFormat::Alpha(true), u32::MAX),
1601            (NumberFormat::Roman(true), 32768),
1602            (NumberFormat::Roman(false), u32::MAX),
1603        ] {
1604            assert_eq!(
1605                format.write(n).as_deref(),
1606                Some(UNREPRESENTABLE),
1607                "{format:?} {n}"
1608            );
1609        }
1610        assert!(
1611            NumberFormat::Roman(true)
1612                .write(32767)
1613                .is_some_and(|r| r.ends_with("MMDCCLXVII"))
1614        );
1615    }
1616
1617    #[test]
1618    fn the_last_format_switch_wins() {
1619        // bn1006: an earlier switch gives way to a later one, "\* CardText
1620        // \* roman" i and "\* Bogus \* roman" i; a format we do not
1621        // write last ("\* roman \* CardText" one) keeps the cache.
1622        let format = |code: &str| number_format(&parse_code(code, &[]));
1623        assert_eq!(
1624            format(" NUMPAGES \\* CardText \\* roman "),
1625            Some(NumberFormat::Roman(false))
1626        );
1627        assert_eq!(
1628            format(" NUMPAGES \\* Bogus \\* roman \\* MERGEFORMAT "),
1629            Some(NumberFormat::Roman(false))
1630        );
1631        assert_eq!(format(" NUMPAGES \\* roman \\* CardText "), None);
1632        assert_eq!(format(" NUMPAGES \\* CardText \\* MERGEFORMAT "), None);
1633    }
1634
1635    #[test]
1636    fn a_numbered_sequence_keeps_counting_in_its_format() {
1637        let mut counters = HashMap::new();
1638        let mut next = |code: &str| sequence(code, &mut counters);
1639        assert_eq!(next(" SEQ Annex \\* ALPHABETIC ").as_deref(), Some("A"));
1640        assert_eq!(next(" SEQ Annex \\* ALPHABETIC ").as_deref(), Some("B"));
1641        assert_eq!(next(" SEQ Annex \\* roman ").as_deref(), Some("iii"));
1642        assert_eq!(next(" SEQ Annex ").as_deref(), Some("4"));
1643        assert_eq!(next(" SEQ Annex \\* Ordinal "), None);
1644        assert_eq!(next(" SEQ Annex "), None);
1645        let mut counters = HashMap::new();
1646        let mut next = |code: &str| sequence(code, &mut counters);
1647        assert_eq!(
1648            next(" SEQ Big \\r 28 \\* alphabetic ").as_deref(),
1649            Some("bb")
1650        );
1651    }
1652
1653    #[test]
1654    fn a_page_reference_formats_a_numeric_page() {
1655        assert_eq!(
1656            format_page("7", &parse_code(" PAGEREF x \\* roman ", &[])).as_deref(),
1657            Some("vii")
1658        );
1659        assert_eq!(
1660            format_page("7", &parse_code(" PAGEREF x \\h ", &[])).as_deref(),
1661            Some("7")
1662        );
1663        // A page labelled by its section ("iii", "2-1") has no number to format.
1664        assert_eq!(
1665            format_page("2-1", &parse_code(" PAGEREF x \\* ROMAN ", &[])),
1666            None
1667        );
1668        assert_eq!(
1669            format_page("2-1", &parse_code(" PAGEREF x ", &[])).as_deref(),
1670            Some("2-1")
1671        );
1672    }
1673
1674    #[test]
1675    fn toc_levels_read_the_outline_switch() {
1676        let levels = |code: &str| toc_levels(&parse_code(code, &["o"]));
1677        assert_eq!(levels(r#" TOC \o "1-3" "#), Some(1..=3));
1678        assert_eq!(levels(r#" TOC \o "2" "#), Some(2..=2));
1679        assert_eq!(levels(" TOC \\h "), Some(1..=9));
1680        assert_eq!(levels(" TOC \\o "), Some(1..=9));
1681        assert_eq!(levels(r#" TOC \o "3-1" "#), None);
1682        assert_eq!(levels(r#" TOC \o "x-2" "#), None);
1683    }
1684
1685    #[test]
1686    fn sequences_count_per_identifier_with_resets_and_repeats() {
1687        let mut counters = HashMap::new();
1688        let mut next = |code: &str| sequence(code, &mut counters);
1689        assert_eq!(next(" SEQ Figure \\* ARABIC ").as_deref(), Some("1"));
1690        assert_eq!(next(" SEQ Table ").as_deref(), Some("1"));
1691        assert_eq!(next(" SEQ Figure ").as_deref(), Some("2"));
1692        assert_eq!(next(" SEQ Figure \\c ").as_deref(), Some("2"));
1693        assert_eq!(next(" SEQ Figure \\r 10 ").as_deref(), Some("10"));
1694        assert_eq!(next(" SEQ Figure \\h ").as_deref(), Some(""));
1695        assert_eq!(next(" SEQ Figure \\n ").as_deref(), Some("12"));
1696        // An unimplemented switch stops the identifier's count.
1697        assert_eq!(next(" SEQ Table \\s 1 "), None);
1698        assert_eq!(next(" SEQ Table "), None);
1699        assert_eq!(next(" SEQ Figure \\r x "), None);
1700        assert_eq!(next(" SEQ Figure "), None);
1701        assert_eq!(next(" SEQ "), None);
1702    }
1703
1704    #[test]
1705    fn heading_levels_come_from_the_style_id_or_name() {
1706        let names: HashMap<String, String> = [("Titre1".to_string(), "heading 1".to_string())]
1707            .into_iter()
1708            .collect();
1709        assert_eq!(heading_level("Heading2", &names), Some(2));
1710        assert_eq!(heading_level("Titre1", &names), Some(1));
1711        assert_eq!(heading_level("Heading10", &names), None);
1712        assert_eq!(heading_level("Normal", &names), None);
1713    }
1714
1715    #[test]
1716    fn toc_style_definitions_indent_by_level() {
1717        assert!(style_definition("TOC3").unwrap().contains("w:left=\"440\""));
1718        assert!(
1719            style_definition("TOCHeading")
1720                .unwrap()
1721                .contains("outlineLvl")
1722        );
1723        assert_eq!(style_definition("TOC10"), None);
1724        assert_eq!(style_definition("Normal"), None);
1725    }
1726}
1727
1728#[cfg(test)]
1729#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1730mod boundary_coverage_tests {
1731    use super::*;
1732
1733    fn document(content: &str) -> (Dom, NodeId) {
1734        let mut dom = Dom::new();
1735        let doc = dom.parse_xdocument(&format!(r#"<w:body xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{content}</w:body>"#));
1736        let root = dom.root(doc).unwrap();
1737        (dom, root)
1738    }
1739
1740    #[test]
1741    fn outline_ranges_reject_each_invalid_endpoint() {
1742        for range in ["0-1", "1-10", "9-1", "1-x", "x-1", "-1", "1-", "256-256"] {
1743            assert_eq!(
1744                toc_levels(&parse_code(&format!(r#"TOC \o "{range}""#), &["o"])),
1745                None,
1746                "{range}"
1747            );
1748        }
1749        for (range, expected) in [("1-9", 1..=9), ("9", 9..=9), (" 2 - 4 ", 2..=4)] {
1750            assert_eq!(
1751                toc_levels(&parse_code(&format!(r#"TOC \o "{range}""#), &["o"])),
1752                Some(expected)
1753            );
1754        }
1755    }
1756
1757    #[test]
1758    fn missing_switch_arguments_never_consume_the_next_switch() {
1759        let code = parse_code(r#"TOC \o \h \@ \z \* \u"#, &["o"]);
1760        assert!(code.args.is_empty());
1761        assert_eq!(
1762            code.switches,
1763            ["o", "h", "@", "z", "*", "u"].map(|s| (s.to_string(), None))
1764        );
1765        assert_eq!(number_format(&code), None);
1766        assert!(!only_switches(&code, &["o", "h", "@", "z", "u"]));
1767        assert!(plain_switches(&code, &["o", "h", "@", "z", "u"]));
1768        assert_eq!(
1769            code_words("REF \"unterminated bookmark"),
1770            vec!["REF", "unterminated bookmark"]
1771        );
1772        assert_eq!(code_words("REF \"\""), vec!["REF", ""]);
1773    }
1774
1775    #[test]
1776    fn formatted_pages_keep_section_labels_only_for_arabic() {
1777        for label in ["iii", "2-1", "", "-1", "4294967296"] {
1778            assert_eq!(
1779                format_page(label, &parse_code("PAGEREF x", &[])),
1780                Some(label.into())
1781            );
1782            assert_eq!(
1783                format_page(label, &parse_code(r"PAGEREF x \* roman", &[])),
1784                None
1785            );
1786        }
1787        assert_eq!(
1788            format_page("12", &parse_code(r"PAGEREF x \* rOMAN", &[])),
1789            Some("xii".into())
1790        );
1791        assert_eq!(
1792            format_page("12", &parse_code(r"PAGEREF x \* Roman", &[])),
1793            Some("XII".into())
1794        );
1795        assert_eq!(
1796            format_page("12", &parse_code(r"PAGEREF x \* Bogus", &[])),
1797            None
1798        );
1799    }
1800
1801    #[test]
1802    fn invalid_sequences_poison_only_their_own_identifier() {
1803        for bad in [
1804            r"SEQ Figure extra",
1805            r"SEQ Figure \r",
1806            r"SEQ Figure \r -1",
1807            r"SEQ Figure \r 4294967296",
1808            r"SEQ Figure \* Hex",
1809            r"SEQ Figure \z",
1810        ] {
1811            let mut counters = HashMap::new();
1812            assert_eq!(sequence("SEQ Figure", &mut counters), Some("1".into()));
1813            assert_eq!(sequence(bad, &mut counters), None, "{bad}");
1814            assert_eq!(sequence(r"SEQ Figure \r 2", &mut counters), None);
1815            assert_eq!(sequence("SEQ Table", &mut counters), Some("1".into()));
1816            assert_eq!(counters.get("Figure"), Some(&None));
1817        }
1818    }
1819
1820    #[test]
1821    fn bookmark_names_skip_taken_names_and_keep_existing_toc_bookmarks() {
1822        let (mut dom, body) = document(
1823            r#"<w:p><w:bookmarkStart w:id="7" w:name="_Toc100000001"/><w:bookmarkEnd w:id="7"/></w:p><w:p><w:pPr/><w:r><w:t>new</w:t></w:r></w:p><w:p><w:bookmarkStart w:id="bad" w:name="ordinary"/><w:r><w:t>other</w:t></w:r></w:p>"#,
1824        );
1825        let paras = dom.elements(body, Some(&W::p()));
1826        let mut namer = BookmarkNamer::new(&dom, body);
1827        assert_eq!(namer.ensure(&mut dom, paras[0]), "_Toc100000001");
1828        assert_eq!(namer.ensure(&mut dom, paras[1]), "_Toc100000002");
1829        assert_eq!(namer.ensure(&mut dom, paras[2]), "_Toc100000003");
1830        let children = dom.elements(paras[1], None);
1831        assert!(dom.name_is(children[0], &W::p_pr()));
1832        assert!(dom.name_is(children[1], &W::bookmark_start()));
1833        assert_eq!(dom.attribute(children[1], &W::id()), Some("8"));
1834        assert!(dom.name_is(*children.last().unwrap(), &W::bookmark_end()));
1835        assert_eq!(
1836            dom.attribute(*children.last().unwrap(), &W::id()),
1837            Some("8")
1838        );
1839        assert_eq!(
1840            bookmark_text(&dom, body, "_Toc100000002"),
1841            Some("new".into())
1842        );
1843        assert_eq!(
1844            bookmark_text(&dom, body, "_Toc100000003"),
1845            Some("other".into())
1846        );
1847        assert_eq!(namer.ensure(&mut dom, paras[1]), "_Toc100000002");
1848    }
1849
1850    #[test]
1851    fn section_text_width_defaults_each_malformed_attribute_and_clamps_small_boxes() {
1852        for (content, expected) in [
1853            ("", 9360),
1854            (
1855                r#"<w:sectPr><w:pgSz w:w="bad"/><w:pgMar w:left="bad" w:right="bad" w:gutter="bad"/></w:sectPr>"#,
1856                9360,
1857            ),
1858            (
1859                r#"<w:sectPr><w:pgSz w:w="10000"/><w:pgMar w:left="1000" w:right="2000" w:gutter="500"/></w:sectPr>"#,
1860                6500,
1861            ),
1862            (
1863                r#"<w:sectPr><w:pgSz w:w="100"/><w:pgMar w:left="0" w:right="0"/></w:sectPr>"#,
1864                720,
1865            ),
1866        ] {
1867            let (dom, body) = document(content);
1868            assert_eq!(text_width(&dom, body), expected);
1869        }
1870    }
1871
1872    #[test]
1873    fn explicit_outline_overrides_named_style_but_invalid_values_fall_back() {
1874        let names = HashMap::from([("Local".into(), "heading 3".into())]);
1875        let (dom, body) = document(
1876            r#"<w:p><w:pPr><w:pStyle w:val="Local"/><w:outlineLvl w:val="0"/></w:pPr><w:r><w:t>  first</w:t><w:tab/><w:t>second  </w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val="Heading2"/><w:outlineLvl w:val="9"/></w:pPr><w:r><w:t>fallback</w:t></w:r></w:p><w:p><w:pPr><w:outlineLvl w:val="bad"/></w:pPr><w:r><w:t>omitted</w:t></w:r></w:p><w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t> </w:t></w:r></w:p>"#,
1877        );
1878        let projected = |outline| {
1879            headings(&dom, body, &names, &(1..=9), outline)
1880                .iter()
1881                .map(|h| (h.level, h.text.clone()))
1882                .collect::<Vec<_>>()
1883        };
1884        assert_eq!(
1885            projected(true),
1886            vec![(1, "first second".into()), (2, "fallback".into())]
1887        );
1888        assert_eq!(
1889            projected(false),
1890            vec![(3, "first second".into()), (2, "fallback".into())]
1891        );
1892        assert!(headings(&dom, body, &names, &(4..=9), true).is_empty());
1893    }
1894}
1895#[cfg(test)]
1896#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1897mod field_story_ownership_tests {
1898    use super::*;
1899    fn body(xml: &str) -> (Dom, NodeId) {
1900        let mut d = Dom::new();
1901        let doc = d.parse_xdocument(&format!(
1902            "<w:body xmlns:w='{}' xmlns:mc='{}' xmlns:v='urn:schemas-microsoft-com:vml'>{xml}</w:body>",
1903            W::URI,
1904            MC::URI
1905        ));
1906        let r = d.root(doc).unwrap();
1907        (d, r)
1908    }
1909    const BEGIN: &str = "<w:r><w:rPr><w:b/></w:rPr><w:fldChar w:fldCharType='begin'/></w:r><w:r><w:instrText> REF Anchor </w:instrText></w:r>";
1910    const SEP: &str = "<w:r><w:fldChar w:fldCharType='separate'/></w:r>";
1911    const END: &str = "<w:r><w:fldChar w:fldCharType='end'/></w:r>";
1912    const CACHE: &str = "<w:r><w:rPr><w:i/><w:color w:val='123456'/></w:rPr><w:t>Old</w:t><w:tab/><w:t>cache</w:t></w:r>";
1913
1914    #[test]
1915    fn field_collector_skips_deleted_fallbacks_and_keeps_textbox_story_stacks_separate() {
1916        for wrapper in ["del", "moveFrom", "mc:Fallback"] {
1917            let tag = if wrapper.starts_with("mc:") {
1918                wrapper.to_string()
1919            } else {
1920                format!("w:{wrapper}")
1921            };
1922            let xml = format!(
1923                "<w:p>{BEGIN}{SEP}<w:fldSimple w:instr='SEQ Body'><w:r><w:t>Body cache</w:t></w:r></w:fldSimple><{tag}><w:fldSimple w:instr='SEQ Gone'><w:r><w:t>Gone cache</w:t></w:r></w:fldSimple></{tag}><w:r><w:pict><v:shape id='Box' style='width:100pt;height:100pt'><v:textbox><w:txbxContent><w:p><w:fldSimple w:instr='SEQ Box'><w:r><w:t>Box cache</w:t></w:r></w:fldSimple></w:p></w:txbxContent></v:textbox></v:shape></w:pict></w:r>{END}</w:p>"
1924            );
1925            let (d, r) = body(&xml);
1926            let before = d.serialize_element(r);
1927            let f = collect_fields(&d, r);
1928            assert_eq!(
1929                f.iter().map(|f| f.kind.as_str()).collect::<Vec<_>>(),
1930                ["REF", "SEQ", "SEQ"]
1931            );
1932            assert_eq!(f[1].in_result_of, Some(0));
1933            assert_eq!(f[2].in_result_of, None);
1934            assert_eq!(result_text(&d, r, &f[1]), "Body cache");
1935            assert_eq!(result_text(&d, r, &f[2]), "Box cache");
1936            let mut results = HashMap::new();
1937            results.insert(0, "replacement".into());
1938            assert!(inside_rewritten_result(&f, 1, &results));
1939            assert!(!inside_rewritten_result(&f, 2, &results));
1940            assert_eq!(d.serialize_element(r), before);
1941        }
1942        let (d, r) = body(&format!(
1943            "<w:p><w:r><w:fldChar w:fldCharType='separate'/><w:instrText>orphan</w:instrText><w:fldChar w:fldCharType='end'/><w:fldChar w:fldCharType='unknown'/></w:r>{BEGIN}<w:fldSimple><w:r><w:t>Empty code cache</w:t></w:r></w:fldSimple></w:p>"
1944        ));
1945        let f = collect_fields(&d, r);
1946        assert_eq!(f.len(), 1);
1947        assert_eq!(f[0].kind, "");
1948        assert_eq!(f[0].in_result_of, None);
1949    }
1950
1951    #[test]
1952    fn cached_result_writes_preserve_field_codes_run_format_and_outside_payload() {
1953        for simple in [false, true] {
1954            for replacement in ["", "New result", " leading & trailing "] {
1955                let xml = if simple {
1956                    format!(
1957                        "<w:p><w:r><w:t>Before</w:t></w:r><w:fldSimple w:instr='REF Anchor'>{CACHE}</w:fldSimple><w:r><w:t>After</w:t></w:r></w:p>"
1958                    )
1959                } else {
1960                    format!(
1961                        "<w:p><w:r><w:t>Before</w:t></w:r>{BEGIN}{SEP}{CACHE}{END}<w:r><w:t>After</w:t></w:r></w:p>"
1962                    )
1963                };
1964                let (mut d, r) = body(&xml);
1965                let f = collect_fields(&d, r);
1966                assert_eq!(f.len(), 1);
1967                assert_eq!(result_text(&d, r, &f[0]), "Old\tcache");
1968                assert!(write_result(&mut d, &f[0], replacement));
1969                let f = collect_fields(&d, r);
1970                assert_eq!(f[0].code.trim(), "REF Anchor");
1971                assert_eq!(result_text(&d, r, &f[0]), replacement);
1972                let texts: Vec<_> = d
1973                    .descendants(r, Some(&W::t()))
1974                    .into_iter()
1975                    .map(|n| d.value(n))
1976                    .collect();
1977                assert_eq!(
1978                    texts,
1979                    if replacement.is_empty() {
1980                        vec!["Before".to_string(), "After".to_string()]
1981                    } else {
1982                        vec![
1983                            "Before".to_string(),
1984                            replacement.to_string(),
1985                            "After".to_string(),
1986                        ]
1987                    }
1988                );
1989                if !replacement.is_empty() {
1990                    let t = d
1991                        .descendants(r, Some(&W::t()))
1992                        .into_iter()
1993                        .find(|&n| d.value(n) == replacement)
1994                        .unwrap();
1995                    let run = d.parent(t).unwrap();
1996                    let rp = d.element(run, &W::r_pr()).unwrap();
1997                    assert!(d.element(rp, &W::name("i")).is_some());
1998                    let color = d.element(rp, &W::name("color")).unwrap();
1999                    assert_eq!(d.attribute(color, &W::val()), Some("123456"));
2000                }
2001            }
2002        }
2003    }
2004
2005    #[test]
2006    fn multi_paragraph_result_is_readable_and_refuses_rewrite_without_mutating_source() {
2007        let xml = format!(
2008            "<w:p><w:pPr><w:keepNext/></w:pPr>{BEGIN}{SEP}{CACHE}</w:p><w:p><w:pPr><w:jc w:val='right'/></w:pPr><w:r><w:t>Second paragraph</w:t></w:r>{END}</w:p>"
2009        );
2010        let (mut d, r) = body(&xml);
2011        let f = collect_fields(&d, r);
2012        assert_eq!(f.len(), 1);
2013        assert_eq!(result_text(&d, r, &f[0]), "Old\tcache\nSecond paragraph");
2014        let before = d.serialize_element(r);
2015        assert!(!write_result(&mut d, &f[0], "replacement"));
2016        assert_eq!(d.serialize_element(r), before);
2017    }
2018
2019    #[test]
2020    fn bookmark_reference_owns_only_live_same_paragraph_text_and_run_tabs() {
2021        for deleted in ["del", "moveFrom"] {
2022            let xml = format!(
2023                "<w:p><w:bookmarkStart w:name='Anchor' w:id='7'/><w:r><w:t>A</w:t><w:tab/><w:t>B</w:t></w:r><w:tab/><w:{deleted}><w:r><w:t>Gone</w:t></w:r></w:{deleted}><w:bookmarkEnd w:id='7'/></w:p>"
2024            );
2025            let (d, r) = body(&xml);
2026            assert_eq!(bookmark_text(&d, r, "Anchor"), Some("A\tB".into()));
2027            assert_eq!(bookmark_text(&d, r, "Missing"), None);
2028        }
2029        for xml in [
2030            "<w:p><w:bookmarkStart w:name='Anchor'/><w:r><w:t>A</w:t></w:r><w:bookmarkEnd w:id='7'/></w:p>",
2031            "<w:p><w:bookmarkStart w:name='Anchor' w:id='7'/><w:r><w:t>A</w:t></w:r><w:bookmarkEnd w:id='8'/></w:p>",
2032            "<w:p><w:bookmarkStart w:name='Anchor' w:id='7'/><w:r><w:t>A</w:t></w:r></w:p><w:p><w:r><w:t>B</w:t></w:r><w:bookmarkEnd w:id='7'/></w:p>",
2033        ] {
2034            let (d, r) = body(xml);
2035            assert_eq!(bookmark_text(&d, r, "Anchor"), None);
2036        }
2037    }
2038}
2039#[cfg(test)]
2040#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2041mod field_cache_boundary_tests {
2042    use super::*;
2043    fn story(xml: &str) -> (Dom, NodeId) {
2044        let mut dom = Dom::new();
2045        let document = dom.parse_xdocument(&format!("<w:body xmlns:w='{}'>{xml}</w:body>", W::URI));
2046        let root = dom.root(document).unwrap();
2047        (dom, root)
2048    }
2049    #[test]
2050    fn absent_and_shared_run_caches_rewrite_without_consuming_field_code_or_neighbor_text() {
2051        for separate in [false, true] {
2052            for replacement in ["", "New & spaced "] {
2053                let cache = if separate {
2054                    "<w:r><w:rPr><w:i/></w:rPr><w:fldChar w:fldCharType='separate'/><w:t>Old</w:t></w:r>"
2055                } else {
2056                    ""
2057                };
2058                let old_end = if separate { "<w:t>tail</w:t>" } else { "" };
2059                let (mut dom, root) = story(&format!(
2060                    "<w:p><w:r><w:t>Before</w:t></w:r><w:r><w:rPr><w:b/></w:rPr><w:fldChar w:fldCharType='begin'/></w:r><w:r><w:instrText> REF Anchor </w:instrText></w:r>{cache}<w:r><w:rPr><w:color w:val='246810'/></w:rPr>{old_end}<w:fldChar w:fldCharType='end'/><w:t>After</w:t></w:r></w:p>"
2061                ));
2062                let f = collect_fields(&dom, root);
2063                assert_eq!(f.len(), 1);
2064                assert_eq!(
2065                    result_text(&dom, root, &f[0]),
2066                    if separate { "Oldtail" } else { "" }
2067                );
2068                assert!(write_result(&mut dom, &f[0], replacement));
2069                let f = collect_fields(&dom, root);
2070                assert_eq!(f[0].code, " REF Anchor ");
2071                assert_eq!(result_text(&dom, root, &f[0]), replacement);
2072                let texts: Vec<_> = dom
2073                    .descendants(root, Some(&W::t()))
2074                    .into_iter()
2075                    .map(|n| dom.value(n))
2076                    .collect();
2077                let expected: Vec<String> = if replacement.is_empty() {
2078                    vec!["Before".into(), "After".into()]
2079                } else {
2080                    vec!["Before".into(), replacement.into(), "After".into()]
2081                };
2082                assert_eq!(texts, expected);
2083                assert_eq!(dom.descendants(root, Some(&W::fld_char())).len(), 3);
2084                let end_run = dom.parent(f[0].end).unwrap();
2085                let rp = dom.element(end_run, &W::r_pr()).unwrap();
2086                assert_eq!(
2087                    dom.attribute(dom.element(rp, &W::name("color")).unwrap(), &W::val()),
2088                    Some("246810")
2089                );
2090                if !replacement.is_empty() {
2091                    let text = dom
2092                        .descendants(root, Some(&W::t()))
2093                        .into_iter()
2094                        .find(|&n| dom.value(n) == replacement)
2095                        .unwrap();
2096                    let rp = dom.element(dom.parent(text).unwrap(), &W::r_pr()).unwrap();
2097                    assert!(dom.element(rp, &W::name("b")).is_some());
2098                    assert_eq!(
2099                        dom.attribute(text, &XNamespace::xml().name("space")),
2100                        Some("preserve")
2101                    );
2102                }
2103            }
2104        }
2105    }
2106    #[test]
2107    fn uncached_toc_creates_entries_and_moves_only_the_original_closing_field_run() {
2108        for links in [false, true] {
2109            let (mut dom, root) = story(
2110                "<w:p><w:pPr><w:pStyle w:val='Title'/><w:spacing w:after='120'/></w:pPr><w:r><w:fldChar w:fldCharType='begin'/></w:r><w:r><w:instrText> TOC </w:instrText></w:r><w:r><w:fldChar w:fldCharType='end'/></w:r><w:r><w:t>After</w:t></w:r></w:p>",
2111            );
2112            let f = collect_fields(&dom, root).remove(0);
2113            let closing = dom.parent(f.end).unwrap();
2114            let entries = vec![
2115                (1, "First".into(), "_Toc1".into()),
2116                (3, "Second".into(), "_Toc2".into()),
2117            ];
2118            assert!(write_toc(&mut dom, &f, &entries, links, 9350));
2119            let ps = dom.elements(root, Some(&W::p()));
2120            assert_eq!(ps.len(), 2);
2121            assert_eq!(dom.parent(closing), Some(ps[1]));
2122            let f = collect_fields(&dom, root);
2123            assert_eq!(f.len(), 3);
2124            assert_eq!(f[0].code, " TOC ");
2125            assert_eq!(f[1].kind, "PAGEREF");
2126            assert_eq!(f[2].kind, "PAGEREF");
2127            assert_eq!(f[1].in_result_of, Some(0));
2128            assert_eq!(f[2].in_result_of, Some(0));
2129            let text: Vec<_> = dom
2130                .descendants(root, Some(&W::t()))
2131                .into_iter()
2132                .map(|n| dom.value(n))
2133                .collect();
2134            assert_eq!(text, vec!["First", "Second", "After"]);
2135            assert_eq!(
2136                dom.descendants(root, Some(&W::hyperlink())).len(),
2137                if links { 2 } else { 0 }
2138            );
2139            for (i, p) in ps.into_iter().enumerate() {
2140                let pr = dom.element(p, &W::p_pr()).unwrap();
2141                assert_eq!(
2142                    dom.attribute(dom.element(pr, &W::p_style()).unwrap(), &W::val()),
2143                    Some(if i == 0 { "Title" } else { "TOC3" })
2144                );
2145                let tabs = dom.element(pr, &W::name("tabs")).unwrap();
2146                let tab = dom.element(tabs, &W::name("tab")).unwrap();
2147                assert_eq!(dom.attribute(tab, &W::name("pos")), Some("9350"));
2148                assert_eq!(dom.attribute(tab, &W::name("leader")), Some("dot"));
2149            }
2150        }
2151    }
2152    #[test]
2153    fn paragraph_style_projection_requires_ids_and_names_and_never_adopts_character_styles() {
2154        let xml = format!(
2155            "<w:styles xmlns:w='{}'><w:style w:type='paragraph' w:styleId='Custom'><w:name w:val='HeAdInG 2'/></w:style><w:style w:type='character' w:styleId='Character'><w:name w:val='Heading 1'/></w:style><w:style w:type='paragraph'><w:name w:val='Heading 3'/></w:style><w:style w:type='paragraph' w:styleId='Nameless'/><w:style w:type='paragraph' w:styleId='Valueless'><w:name/></w:style></w:styles>",
2156            W::URI
2157        );
2158        assert_eq!(
2159            paragraph_style_names(&xml),
2160            HashMap::from([("Custom".to_string(), "heading 2".to_string())])
2161        );
2162        for invalid in ["", "TOC", "TOCx", "TOC0", "TOC10", "Heading1"] {
2163            assert!(style_definition(invalid).is_none(), "{invalid}");
2164        }
2165        for level in 1..=9 {
2166            let xml = style_definition(&format!("TOC{level}")).unwrap();
2167            assert!(xml.contains(&format!("w:left=\"{}\"", (level - 1) * 220)));
2168            assert!(xml.contains(&format!("w:styleId=\"TOC{level}\"")));
2169        }
2170        assert!(
2171            style_definition("TOCHeading")
2172                .unwrap()
2173                .contains("w:val=\"9\"")
2174        );
2175    }
2176}
2177#[cfg(test)]
2178#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2179mod field_decline_source_boundary_tests {
2180    use super::*;
2181
2182    fn story(body: &str) -> Story {
2183        let mut dom = Dom::new();
2184        let document =
2185            dom.parse_xdocument(&format!(r#"<w:body xmlns:w="{}">{body}</w:body>"#, W::URI));
2186        let root = dom.root(document).unwrap();
2187        Story {
2188            id: "body".to_string(),
2189            part: "word/document.xml".to_string(),
2190            dom,
2191            document,
2192            root,
2193            body: true,
2194            changed: false,
2195        }
2196    }
2197
2198    const BEGIN: &str = "<w:r><w:rPr><w:b/></w:rPr><w:fldChar w:fldCharType='begin'/></w:r><w:r><w:instrText> TOC </w:instrText></w:r>";
2199    const SEPARATE: &str = "<w:r><w:fldChar w:fldCharType='separate'/></w:r>";
2200    const CACHE: &str =
2201        "<w:r><w:rPr><w:i/><w:color w:val='123456'/></w:rPr><w:t>owned cache</w:t></w:r>";
2202    const END: &str =
2203        "<w:r><w:rPr><w:u w:val='single'/></w:rPr><w:fldChar w:fldCharType='end'/></w:r>";
2204
2205    #[test]
2206    fn toc_declines_unhandled_legal_marker_containers_without_changing_any_source_node() {
2207        let cases=vec![
2208            "<w:p><w:pPr><w:spacing w:after='120'/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:fldChar w:fldCharType='begin'/><w:instrText> TOC </w:instrText><w:fldChar w:fldCharType='separate'/><w:t>owned cache</w:t><w:fldChar w:fldCharType='end'/></w:r></w:p>".to_string(),
2209            format!("<w:p>{BEGIN}</w:p><w:p><w:r><w:rPr><w:i/></w:rPr><w:fldChar w:fldCharType='separate'/><w:t>owned cache</w:t><w:fldChar w:fldCharType='end'/></w:r></w:p>"),
2210            format!("<w:p><w:hyperlink w:anchor='target'>{BEGIN}</w:hyperlink>{SEPARATE}{CACHE}{END}<w:bookmarkStart w:id='3' w:name='target'/><w:bookmarkEnd w:id='3'/></w:p>"),
2211            format!("<w:p>{BEGIN}{SEPARATE}{CACHE}<w:hyperlink w:anchor='target'>{END}</w:hyperlink><w:bookmarkStart w:id='3' w:name='target'/><w:bookmarkEnd w:id='3'/></w:p>"),
2212            format!("<w:p>{BEGIN}</w:p><w:p>{SEPARATE}{CACHE}</w:p><w:p>{END}</w:p>"),
2213        ];
2214        let entries = vec![(1, "authored heading".to_string(), "_Toc1".to_string())];
2215        for source in cases {
2216            let mut story = story(&source);
2217            let fields = collect_fields(&story.dom, story.root);
2218            assert_eq!(fields.len(), 1);
2219            assert_eq!(fields[0].kind, "TOC");
2220            assert!(!fields[0].simple);
2221            let frozen = story.dom.serialize_element(story.root);
2222            assert!(
2223                !write_toc(&mut story.dom, &fields[0], &entries, true, 9350),
2224                "{source}"
2225            );
2226            assert_eq!(story.dom.serialize_element(story.root), frozen, "{source}");
2227            assert_eq!(
2228                result_text(&story.dom, story.root, &fields[0]),
2229                "owned cache"
2230            );
2231        }
2232    }
2233
2234    #[test]
2235    fn unsupported_and_nested_tocs_preserve_cache_heading_properties_and_bookmark_ids() {
2236        let heading = "<w:p><w:pPr><w:pStyle w:val='Heading1'/><w:spacing w:after='240'/></w:pPr><w:bookmarkStart w:id='4' w:name='owned'/><w:r><w:rPr><w:b/></w:rPr><w:t>authored heading</w:t></w:r><w:bookmarkEnd w:id='4'/></w:p>";
2237        for field in [
2238            format!("<w:p><w:fldSimple w:instr=' TOC '>{CACHE}</w:fldSimple></w:p>"),
2239            format!(
2240                "<w:p><w:r><w:fldChar w:fldCharType='begin'/></w:r><w:r><w:instrText> REF owned </w:instrText></w:r>{SEPARATE}{BEGIN}{SEPARATE}{CACHE}{END}<w:r><w:fldChar w:fldCharType='end'/></w:r></w:p>"
2241            ),
2242            format!(
2243                "<w:p>{}{SEPARATE}{CACHE}{END}</w:p>",
2244                BEGIN.replace(" TOC ", " TOC stray ")
2245            ),
2246            format!(
2247                "<w:p>{}{SEPARATE}{CACHE}{END}</w:p>",
2248                BEGIN.replace(" TOC ", " TOC \\t &quot;Heading 1,1&quot; ")
2249            ),
2250            format!(
2251                "<w:p>{}{SEPARATE}{CACHE}{END}</w:p>",
2252                BEGIN.replace(" TOC ", " TOC \\o &quot;9-1&quot; ")
2253            ),
2254        ] {
2255            let mut story = story(&format!("{field}{heading}"));
2256            let frozen = story.dom.serialize_element(story.root);
2257            assert!(
2258                collect_fields(&story.dom, story.root)
2259                    .iter()
2260                    .any(|field| field.kind == "TOC")
2261            );
2262            let result = rebuild_tocs(&mut story, &HashMap::new());
2263            assert!(result.rebuilt.is_empty());
2264            assert_eq!(result.max_level, 0);
2265            assert!(!story.changed);
2266            assert_eq!(story.dom.serialize_element(story.root), frozen);
2267        }
2268    }
2269}
2270
2271#[cfg(test)]
2272#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2273mod authored_field_projection_contract_tests {
2274    use super::*;
2275
2276    fn story(source: &str, body: bool) -> Story {
2277        let mut dom = Dom::new();
2278        let document =
2279            dom.parse_xdocument(&format!("<w:body xmlns:w='{}'>{source}</w:body>", W::URI));
2280        let root = dom.root(document).unwrap();
2281        Story {
2282            id: if body { "body" } else { "header1" }.into(),
2283            part: if body {
2284                "word/document.xml"
2285            } else {
2286                "word/header1.xml"
2287            }
2288            .into(),
2289            dom,
2290            document,
2291            root,
2292            body,
2293            changed: false,
2294        }
2295    }
2296
2297    #[test]
2298    fn unsupported_field_arguments_keep_their_complete_authored_cache() {
2299        let facts = jubarte_render::convert::LayoutFacts {
2300            page_count: 7,
2301            ..Default::default()
2302        };
2303        let defined = BTreeSet::from(["anchor".to_string()]);
2304        let context = Context {
2305            facts: &facts,
2306            defined: &defined,
2307        };
2308        for body in [false, true] {
2309            for (code, expected) in [
2310                ("NUMPAGES", Some("7")),
2311                ("NUMPAGES extra", None),
2312                ("NUMPAGES \\x", None),
2313                ("PAGEREF", None),
2314                ("PAGEREF anchor extra", None),
2315                ("REF", None),
2316                ("REF anchor extra", None),
2317                ("SEQ owned", if body { Some("1") } else { None }),
2318            ] {
2319                let source = format!(
2320                    "<w:p><w:pPr><w:spacing w:after='120'/></w:pPr><w:fldSimple w:instr='{code}'><w:r><w:rPr><w:i/><w:color w:val='246810'/></w:rPr><w:t>owned cache</w:t><w:tab/><w:t>tail</w:t></w:r></w:fldSimple><w:r><w:t>outside</w:t></w:r></w:p>"
2321                );
2322                let story = story(&source, body);
2323                let frozen = story.dom.serialize_element(story.root);
2324                let fields = collect_fields(&story.dom, story.root);
2325                assert_eq!(fields.len(), 1, "{code}");
2326                let results = results_for(&story, &fields, &context);
2327                assert_eq!(
2328                    results.get(&0).map(String::as_str),
2329                    expected,
2330                    "body={body}, {code}"
2331                );
2332                assert_eq!(
2333                    result_text(&story.dom, story.root, &fields[0]),
2334                    "owned cache\ttail"
2335                );
2336                assert_eq!(story.dom.serialize_element(story.root), frozen);
2337            }
2338        }
2339    }
2340
2341    #[test]
2342    fn nested_field_results_belong_to_the_outer_replacement_only() {
2343        let source = "<w:p><w:r><w:fldChar w:fldCharType='begin'/></w:r><w:r><w:instrText> NUMPAGES </w:instrText></w:r><w:r><w:fldChar w:fldCharType='separate'/></w:r><w:r><w:t>outer</w:t></w:r><w:r><w:fldChar w:fldCharType='begin'/></w:r><w:r><w:instrText> NUMPAGES </w:instrText></w:r><w:r><w:fldChar w:fldCharType='separate'/></w:r><w:r><w:rPr><w:b/></w:rPr><w:t>inner</w:t></w:r><w:r><w:fldChar w:fldCharType='end'/></w:r><w:r><w:t>tail</w:t></w:r><w:r><w:fldChar w:fldCharType='end'/></w:r><w:r><w:t>outside</w:t></w:r></w:p>";
2344        let mut story = story(source, true);
2345        let fields = collect_fields(&story.dom, story.root);
2346        assert_eq!(fields.len(), 2);
2347        assert_eq!(fields[1].in_result_of, Some(0));
2348        let results = HashMap::from([(0, "7".to_string()), (1, "7".to_string())]);
2349        assert!(!inside_rewritten_result(&fields, 0, &results));
2350        assert!(inside_rewritten_result(&fields, 1, &results));
2351        assert!(!inside_rewritten_result(
2352            &fields,
2353            1,
2354            &HashMap::from([(1, "7".to_string())])
2355        ));
2356        assert!(write_result(&mut story.dom, &fields[0], "7"));
2357        let remaining = collect_fields(&story.dom, story.root);
2358        assert_eq!(remaining.len(), 1);
2359        assert_eq!(remaining[0].code, " NUMPAGES ");
2360        assert_eq!(result_text(&story.dom, story.root, &remaining[0]), "7");
2361        let text: Vec<_> = story
2362            .dom
2363            .descendants(story.root, Some(&W::t()))
2364            .into_iter()
2365            .map(|n| story.dom.value(n))
2366            .collect();
2367        assert_eq!(text, ["7", "outside"]);
2368    }
2369
2370    #[test]
2371    fn splitting_combined_mark_runs_keeps_consecutive_code_and_result_nodes_in_order() {
2372        let mut story = story(
2373            "<w:p><w:r w:rsidR='01234567'><w:rPr><w:b/><w:color w:val='135790'/></w:rPr><w:fldChar w:fldCharType='begin'/><w:instrText> REF </w:instrText><w:instrText>anchor </w:instrText><w:fldChar w:fldCharType='separate'/><w:t>first</w:t><w:tab/><w:t>last</w:t><w:fldChar w:fldCharType='end'/></w:r></w:p>",
2374            true,
2375        );
2376        assert!(split_mark_runs(&mut story.dom, story.root));
2377        let fields = collect_fields(&story.dom, story.root);
2378        assert_eq!(fields.len(), 1);
2379        assert_eq!(fields[0].code, " REF anchor ");
2380        assert_eq!(
2381            result_text(&story.dom, story.root, &fields[0]),
2382            "first\tlast"
2383        );
2384        let runs = story.dom.descendants(story.root, Some(&W::r()));
2385        assert_eq!(runs.len(), 5);
2386        for run in runs {
2387            assert_eq!(story.dom.attribute(run, &W::rsid_r()), Some("01234567"));
2388            let properties = story.dom.element(run, &W::r_pr()).unwrap();
2389            assert!(story.dom.element(properties, &W::name("b")).is_some());
2390            let color = story.dom.element(properties, &W::name("color")).unwrap();
2391            assert_eq!(story.dom.attribute(color, &W::val()), Some("135790"));
2392        }
2393        let frozen = story.dom.serialize_element(story.root);
2394        assert!(!split_mark_runs(&mut story.dom, story.root));
2395        assert_eq!(story.dom.serialize_element(story.root), frozen);
2396    }
2397
2398    #[test]
2399    fn missing_style_insertion_preserves_existing_and_alternate_prefix_parts() {
2400        for source in [
2401            None,
2402            Some(
2403                "<w:styles xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'><w:style w:styleId=\"TOC1\" w:type='paragraph'><w:name w:val='owned custom TOC'/></w:style></w:styles>",
2404            ),
2405            Some(
2406                "<x:styles xmlns:x='http://schemas.openxmlformats.org/wordprocessingml/2006/main'><x:style x:styleId='Owned'/></x:styles>",
2407            ),
2408        ] {
2409            let mut pkg = PartFs::open(&tests::tiny_docx("<w:p/>")).unwrap();
2410            if let Some(source) = source {
2411                pkg.set_part("word/styles.xml", source.as_bytes().to_vec());
2412            }
2413            let frozen = pkg.part_bytes("word/document.xml").unwrap().to_vec();
2414            add_missing_styles(
2415                &mut pkg,
2416                "word/styles.xml",
2417                &BTreeSet::from(["TOC1".into()]),
2418            );
2419            assert_eq!(pkg.part_string("word/styles.xml").as_deref(), source);
2420            assert_eq!(pkg.part_bytes("word/document.xml").unwrap(), frozen);
2421        }
2422    }
2423}