jubarte-markdown 0.20.0

Markdown in and out of Word documents for the jubarte engine: CriticMarkup as tracked changes, the agent view, and .doc reading
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
//
// SPDX-License-Identifier: Apache-2.0

//! The custom XML data stores of the content controls the writer writes
//! bound to one (#1427).
//!
//! (This module stays in the markdown layer: its builder walks the
//! writer's Element model from `super::from_docx`. The lookup half it
//! names `crate::data_stores` lives in the opc crate's `data_stores`.)
//!
//! Word fills a bound control (`w:sdtPr/w:dataBinding`) from its store when
//! it opens the file. A drawing payload (a cover page's text box) keeps its
//! controls' bindings, but the store is a package part the drawing never
//! reaches: without it Word shows the control empty. So for every store a
//! written binding names and the main part does not reach, the writer
//! builds one from the bindings themselves: each simple path
//! (`/ns0:CoverPageProperties[1]/ns0:Abstract[1]`) a node holding what its
//! control shows. Only a plain text, date or list control's value is
//! its text; any other binding (rich text, a picture, a check box, a path
//! that is not simple, content plain text cannot hold) loses its
//! `w:dataBinding` instead, so Word keeps what the control shows. (A box
//! whose words the view edits is written with plain runs, no control, so
//! the edit shows as written.)

use std::fmt::Write as _;
use std::sync::Arc;

use quick_xml::Reader;
use quick_xml::events::{BytesStart, Event};

use super::from_docx::{Element, element_from, parse_xml};
use super::xml::escape;
use crate::opc::{PartFs, relative_rel_target};
#[doc(hidden)]
pub use jubarte_opc::data_stores::{built_in, stores};

const RELS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
const DS_NS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/customXml";
const PROPS_CT: &str = "application/vnd.openxmlformats-officedocument.customXmlProperties+xml";

/// One control's binding: its store, the path's steps (namespace URI and
/// local name; `None` when the path is not a simple one), and the value
/// its store holds (`None` when no value of the control's own is one).
struct Binding {
    store: String,
    xpath: String,
    steps: Option<Vec<(String, String)>>,
    value: Option<String>,
}

/// A node of a store being built.
struct Node {
    namespace: String,
    local: String,
    value: Option<String>,
    children: Vec<Node>,
}

/// Write the stores the written parts' bindings name and the main part
/// does not reach; drop the bindings no store can be built for.
pub(crate) fn write_missing(package: &mut PartFs, main: &str, warnings: &mut Vec<String>) {
    let held = stores(package, main);
    let mut parts: Vec<(String, Vec<Binding>)> = Vec::new();
    for part in package.parts() {
        if !part.ends_with(".xml") || part.starts_with("customXml/") {
            continue;
        }
        let Some(bytes) = package.part_bytes(&part) else {
            continue;
        };
        if !bytes.windows(11).any(|w| w == b"dataBinding") {
            continue;
        }
        let Some(root) = std::str::from_utf8(bytes)
            .ok()
            .and_then(|xml| parse_xml(xml.as_bytes()).ok())
        else {
            warnings.push(format!(
                "{part} could not be read for its bound controls; their stores are not written"
            ));
            continue;
        };
        let mut found = Vec::new();
        bindings(&root, &mut found);
        found.retain(|b| !built_in(&b.store) && !held.contains(&b.store.to_ascii_uppercase()));
        if !found.is_empty() {
            parts.push((part, found));
        }
    }
    // Each store's nodes, in the order the parts name them.
    let mut built: Vec<(String, Node)> = Vec::new();
    let mut unbuilt: Vec<(String, String, String)> = Vec::new();
    for (part, found) in &parts {
        for b in found {
            let placed = match (&b.steps, &b.value) {
                (Some(steps), Some(value)) => {
                    let at = match built
                        .iter()
                        .position(|(id, _)| id.eq_ignore_ascii_case(&b.store))
                    {
                        Some(at) => at,
                        None => {
                            let (namespace, local) = steps[0].clone();
                            built.push((
                                b.store.clone(),
                                Node {
                                    namespace,
                                    local,
                                    value: None,
                                    children: Vec::new(),
                                },
                            ));
                            built.len() - 1
                        }
                    };
                    match insert(&mut built[at].1, steps, value) {
                        Placed::Conflict(first) => {
                            warnings.push(format!(
                                "{part}: two controls bind {} with different text; the store holds the first, {first:?}",
                                b.xpath
                            ));
                            true
                        }
                        Placed::Yes => true,
                        Placed::Elsewhere => false,
                    }
                }
                _ => false,
            };
            if !placed {
                unbuilt.push((part.clone(), b.store.clone(), b.xpath.clone()));
            }
        }
    }
    for (store, root) in &built {
        write_store(package, main, store, root);
    }
    for (part, store, xpath) in unbuilt {
        let Some(xml) = package
            .part_bytes(&part)
            .and_then(|bytes| std::str::from_utf8(bytes).ok())
        else {
            continue;
        };
        let xml = unbound(xml, &store, &xpath);
        package.set_part(&part, xml.into_bytes());
    }
}

/// Every bound control under `e`, nested ones too.
fn bindings(e: &Element, out: &mut Vec<Binding>) {
    for c in e.elements() {
        if c.is("sdt")
            && let Some(binding) = c.path(&["sdtPr", "dataBinding"])
            && let Some(store) = binding.attr("storeItemID")
        {
            let xpath = binding.attr("xpath").unwrap_or_default().to_string();
            let prefixes = prefix_mappings(binding.attr("prefixMappings").unwrap_or_default());
            out.push(Binding {
                store: store.to_string(),
                steps: steps(&xpath, &prefixes),
                xpath,
                value: shown(c),
            });
        }
        bindings(c, out);
    }
}

/// `xmlns:ns0='uri' xmlns:ns1="uri"` as (prefix, URI) pairs.
fn prefix_mappings(text: &str) -> Vec<(String, String)> {
    let mut out = Vec::new();
    let mut rest = text;
    while let Some(at) = rest.find("xmlns:") {
        rest = &rest[at + "xmlns:".len()..];
        let Some((prefix, after)) = rest.split_once('=') else {
            break;
        };
        let Some(quote) = after.chars().next().filter(|c| *c == '\'' || *c == '"') else {
            break;
        };
        let Some((uri, tail)) = after[1..].split_once(quote) else {
            break;
        };
        out.push((prefix.trim().to_string(), uri.to_string()));
        rest = tail;
    }
    out
}

/// A simple path's steps: `/p:a[1]/p:b[1]`, each a mapped prefix's name,
/// the first of its name (`[1]` or no index). `None` for anything else,
/// an unprefixed name too (XPath 1.0 puts it in no namespace).
fn steps(xpath: &str, prefixes: &[(String, String)]) -> Option<Vec<(String, String)>> {
    let rest = xpath.strip_prefix('/')?;
    let steps = rest
        .split('/')
        .map(|step| {
            let name = step.strip_suffix("[1]").unwrap_or(step);
            let (prefix, local) = name.split_once(':')?;
            // An NCName: a letter or `_`, then letters, digits, `_-.`.
            let simple = |s: &str| {
                s.chars()
                    .next()
                    .is_some_and(|c| c.is_alphabetic() || c == '_')
                    && s.chars()
                        .all(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | '.'))
            };
            if !simple(prefix) || !simple(local) {
                return None;
            }
            let namespace = prefixes.iter().find(|(p, _)| p == prefix)?.1.clone();
            Some((namespace, local.to_string()))
        })
        .collect::<Option<Vec<_>>>()?;
    (!steps.is_empty()).then_some(steps)
}

/// What a control shows, as its store holds it: nothing
/// while it shows its placeholder; a date control's date as its
/// `w:storeMappedDataAs` asks; a list's chosen item's value; a plain text
/// control's text. `None` for the rest, whose store value is not their
/// text (rich text, a picture, a check box), and for content plain text
/// cannot hold (a field, a symbol, a second paragraph): those lose their
/// binding instead.
fn shown(sdt: &Element) -> Option<String> {
    let properties = sdt.child("sdtPr")?;
    let kind = ["text", "date", "dropDownList", "comboBox"]
        .into_iter()
        .find(|kind| properties.child(kind).is_some())?;
    if properties.child("showingPlcHdr").is_some() {
        return Some(String::new());
    }
    let mut text = String::new();
    let mut paragraphs = 0;
    if let Some(content) = sdt.child("sdtContent") {
        plain(content, &mut text, &mut paragraphs)?;
    }
    let control = properties.child(kind)?;
    match kind {
        "date" => {
            let full = control.attr("fullDate");
            match control
                .child("storeMappedDataAs")
                .and_then(|s| s.attr("val"))
                .unwrap_or("dateTime")
            {
                "text" => Some(text),
                "date" => full.and_then(|d| d.split('T').next()).map(str::to_string),
                _ => full.map(str::to_string),
            }
        }
        "dropDownList" | "comboBox" => {
            let chosen = control.children_named("listItem").find(|item| {
                item.attr("displayText").or_else(|| item.attr("value")) == Some(text.as_str())
            });
            match chosen {
                Some(item) => item.attr("value").map(str::to_string),
                None if kind == "comboBox" => Some(text),
                None => None,
            }
        }
        _ => Some(text),
    }
}

/// The text a plain text control's runs show: `w:t`, a tab, a break.
/// `None` at anything plain text does not hold.
fn plain(e: &Element, out: &mut String, paragraphs: &mut usize) -> Option<()> {
    for c in e.elements() {
        match c.local() {
            "t" => out.push_str(&c.text()),
            "tab" => out.push('\t'),
            "br" | "cr" => out.push('\n'),
            "p" => {
                *paragraphs += 1;
                if *paragraphs > 1 {
                    return None;
                }
                plain(c, out, paragraphs)?;
            }
            "r" | "ins" | "moveTo" | "hyperlink" | "smartTag" | "customXml" | "sdt"
            | "sdtContent" | "bdo" | "dir" => plain(c, out, paragraphs)?,
            // Properties, and text the control no longer shows.
            "pPr" | "rPr" | "sdtPr" | "sdtEndPr" | "del" | "moveFrom" => {}
            // A marker (a bookmark, a comment's range) shows nothing.
            _ if c.children.is_empty() && !SHOWS.contains(&c.local()) => {}
            _ => return None,
        }
    }
    Some(())
}

/// Empty run content that shows something plain text cannot hold.
const SHOWS: [&str; 16] = [
    "fldChar",
    "sym",
    "ptab",
    "noBreakHyphen",
    "softHyphen",
    "footnoteReference",
    "endnoteReference",
    "pgNum",
    "dayShort",
    "dayLong",
    "monthShort",
    "monthLong",
    "yearShort",
    "yearLong",
    "annotationRef",
    "separator",
];

/// Where [`insert`] put a value.
enum Placed {
    Yes,
    /// The node already held another value, kept.
    Conflict(String),
    /// The path starts at another root.
    Elsewhere,
}

/// Put `value` at `steps` under `root` (whose own step is `steps[0]`).
/// The first value a node gets is kept: a drawing's fallback repeats its
/// controls, with the same text.
fn insert(root: &mut Node, steps: &[(String, String)], value: &str) -> Placed {
    let (namespace, local) = &steps[0];
    if *namespace != root.namespace || *local != root.local {
        return Placed::Elsewhere;
    }
    let mut node = root;
    for (namespace, local) in &steps[1..] {
        let at = match node
            .children
            .iter()
            .position(|c| c.namespace == *namespace && c.local == *local)
        {
            Some(at) => at,
            None => {
                node.children.push(Node {
                    namespace: namespace.clone(),
                    local: local.clone(),
                    value: None,
                    children: Vec::new(),
                });
                node.children.len() - 1
            }
        };
        node = &mut node.children[at];
    }
    match &node.value {
        None => {
            node.value = Some(value.to_string());
            Placed::Yes
        }
        Some(first) if first == value => Placed::Yes,
        Some(first) => Placed::Conflict(first.clone()),
    }
}

/// The namespaces a store's nodes use, in the order they use them.
fn namespaces(root: &Node) -> Vec<&str> {
    fn walk<'a>(node: &'a Node, out: &mut Vec<&'a str>) {
        if !out.contains(&node.namespace.as_str()) {
            out.push(&node.namespace);
        }
        for c in &node.children {
            walk(c, out);
        }
    }
    let mut out = Vec::new();
    walk(root, &mut out);
    out
}

/// The store as XML: one namespace as the root's default, as Word writes
/// a cover page's; several declared once on the root, `ns0`, `ns1`, … in
/// the order the nodes use them.
fn store_xml(root: &Node) -> String {
    fn element(node: &Node, uris: &[&str], declarations: &str, out: &mut String) {
        let name = match uris {
            [_] => node.local.clone(),
            _ => {
                let prefix = uris.iter().position(|u| *u == node.namespace).unwrap_or(0);
                format!("ns{prefix}:{}", node.local)
            }
        };
        let _ = write!(out, "<{name}{declarations}");
        // A node bound whole and in parts (a repeating section's item)
        // holds its parts.
        match (&node.value, node.children.is_empty()) {
            (_, false) => {
                out.push('>');
                for c in &node.children {
                    element(c, uris, "", out);
                }
                let _ = write!(out, "</{name}>");
            }
            (Some(value), true) if !value.is_empty() => {
                let _ = write!(out, ">{}</{name}>", escape(value));
            }
            (_, true) => out.push_str("/>"),
        }
    }
    let uris = namespaces(root);
    let declarations: String = match uris.as_slice() {
        [uri] => format!(" xmlns=\"{}\"", escape(uri)),
        _ => uris
            .iter()
            .enumerate()
            .map(|(i, uri)| format!(" xmlns:ns{i}=\"{}\"", escape(uri)))
            .collect(),
    };
    let mut out = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
    element(root, &uris, &declarations, &mut out);
    out
}

/// Write `customXml/itemN.xml` with its `itemPropsN.xml`, related from the
/// main document part.
fn write_store(package: &mut PartFs, main: &str, store: &str, root: &Node) {
    let parts = package.parts();
    let n = (1..)
        .find(|n| {
            let taken = |name: String| parts.iter().any(|p| p.eq_ignore_ascii_case(&name));
            // Nor a stale relationship part of the item's.
            !taken(format!("customXml/item{n}.xml"))
                && !taken(format!("customXml/itemProps{n}.xml"))
                && package
                    .read_rels_for(&format!("customXml/item{n}.xml"))
                    .is_none()
        })
        .unwrap_or(1);
    let item = format!("customXml/item{n}.xml");
    let props = format!("customXml/itemProps{n}.xml");
    package.set_part(&item, store_xml(root).into_bytes());
    let schemas: String = namespaces(root)
        .iter()
        .map(|uri| format!("<ds:schemaRef ds:uri=\"{}\"/>", escape(uri)))
        .collect();
    package.set_part(
        &props,
        format!(
            "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\
             <ds:datastoreItem ds:itemID=\"{}\" xmlns:ds=\"{DS_NS}\">\
             <ds:schemaRefs>{schemas}</ds:schemaRefs></ds:datastoreItem>",
            escape(store)
        )
        .into_bytes(),
    );
    if package.content_type_for(&format!("/{item}")).is_none() {
        package.add_content_type_override(&format!("/{item}"), "application/xml");
    }
    package.add_content_type_override(&format!("/{props}"), PROPS_CT);
    package.add_document_relationship(
        &item,
        &format!("{RELS}/customXmlProps"),
        &format!("itemProps{n}.xml"),
    );
    package.add_document_relationship(
        main,
        &format!("{RELS}/customXml"),
        &relative_rel_target(main, &item),
    );
}

/// `xml` without the `dataBinding` elements that bind `store` at `xpath`,
/// read as the parser reads them (either quote, entities, an element
/// closed by its own end tag).
fn unbound(xml: &str, store: &str, xpath: &str) -> String {
    let binds = |start: &BytesStart<'_>| {
        element_from(start, &Arc::default()).is_ok_and(|e| {
            e.is("dataBinding")
                && e.attr("storeItemID")
                    .is_some_and(|s| s.eq_ignore_ascii_case(store))
                && e.attr("xpath") == Some(xpath)
        })
    };
    let mut reader = Reader::from_str(xml);
    reader.config_mut().trim_text(false);
    let mut cuts: Vec<(usize, usize)> = Vec::new();
    let mut open: Option<(usize, String)> = None;
    loop {
        let before = reader.buffer_position() as usize;
        let Ok(event) = reader.read_event() else {
            break;
        };
        let after = reader.buffer_position() as usize;
        match (&event, &open) {
            (Event::Eof, _) => break,
            (Event::Empty(start), None) if binds(start) => cuts.push((before, after)),
            (Event::Start(start), None) if binds(start) => {
                open = Some((before, start.name().as_ref().to_string()));
            }
            (Event::End(end), Some((from, name))) if end.name().as_ref() == name => {
                cuts.push((*from, after));
                open = None;
            }
            _ => {}
        }
    }
    let mut out = String::with_capacity(xml.len());
    let mut at = 0;
    for (from, to) in cuts {
        out.push_str(&xml[at..from]);
        at = to;
    }
    out.push_str(&xml[at..]);
    out
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod tests {
    use super::*;

    const COVER: &str = "http://schemas.microsoft.com/office/2006/coverPageProps";

    #[test]
    fn a_simple_path_reads_as_its_steps() {
        let prefixes = prefix_mappings(&format!("xmlns:ns0='{COVER}' xmlns:ns1=\"urn:b\""));
        assert_eq!(
            prefixes,
            vec![
                ("ns0".to_string(), COVER.to_string()),
                ("ns1".to_string(), "urn:b".to_string())
            ]
        );
        assert_eq!(
            steps("/ns0:CoverPageProperties[1]/ns1:Abstract", &prefixes),
            Some(vec![
                (COVER.to_string(), "CoverPageProperties".to_string()),
                ("urn:b".to_string(), "Abstract".to_string())
            ])
        );
        for odd in [
            "ns0:Root[1]",
            "/ns0:Root[2]",
            "/ns0:Root[1]/@ns0:attr",
            "/nsX:Root[1]",
            "/ns0:Root[1]//ns0:Any",
            "/Root",
            "",
        ] {
            assert_eq!(steps(odd, &prefixes), None, "{odd}");
        }
    }

    #[test]
    fn a_store_holds_each_path_once_under_one_root() {
        let cover = |local: &str| (COVER.to_string(), local.to_string());
        let mut root = Node {
            namespace: COVER.to_string(),
            local: "CoverPageProperties".to_string(),
            value: None,
            children: Vec::new(),
        };
        let abstract_ = [cover("CoverPageProperties"), cover("Abstract")];
        assert!(matches!(
            insert(&mut root, &abstract_, "A & b"),
            Placed::Yes
        ));
        // A fallback's copy agrees; another control's other text does not.
        assert!(matches!(
            insert(&mut root, &abstract_, "A & b"),
            Placed::Yes
        ));
        assert!(matches!(
            insert(&mut root, &abstract_, "later"),
            Placed::Conflict(first) if first == "A & b"
        ));
        assert!(matches!(
            insert(
                &mut root,
                &[cover("CoverPageProperties"), cover("PublishDate")],
                ""
            ),
            Placed::Yes
        ));
        assert!(matches!(
            insert(&mut root, &[cover("Other"), cover("Abstract")], "x"),
            Placed::Elsewhere
        ));
        // One namespace is the root's default, as Word writes it.
        assert_eq!(
            store_xml(&root),
            format!(
                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\
                 <CoverPageProperties xmlns=\"{COVER}\"><Abstract>A &amp; b</Abstract>\
                 <PublishDate/></CoverPageProperties>"
            )
        );
        insert(
            &mut root,
            &[
                cover("CoverPageProperties"),
                ("urn:b".to_string(), "Extra".to_string()),
            ],
            "e",
        );
        assert_eq!(namespaces(&root), [COVER, "urn:b"]);
        assert_eq!(
            store_xml(&root),
            format!(
                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\
                 <ns0:CoverPageProperties xmlns:ns0=\"{COVER}\" xmlns:ns1=\"urn:b\">\
                 <ns0:Abstract>A &amp; b</ns0:Abstract><ns0:PublishDate/><ns1:Extra>e</ns1:Extra>\
                 </ns0:CoverPageProperties>"
            )
        );
    }

    #[test]
    fn a_name_that_is_no_ncname_is_no_step() {
        let prefixes = prefix_mappings("xmlns:ns0='urn:x'");
        for odd in ["/ns0:-bad[1]", "/ns0:.bad", "/ns0:1bad", "/ns0:a b"] {
            assert_eq!(steps(odd, &prefixes), None, "{odd}");
        }
        assert!(steps("/ns0:_ok-1.2[1]", &prefixes).is_some());
    }

    #[test]
    fn a_control_s_store_value_is_its_text_only_where_word_keeps_it_so() {
        let sdt = |pr: &str, content: &str| {
            parse_xml(
                format!(
                    "<w:sdt xmlns:w=\"urn:w\" xmlns:w14=\"urn:w14\"><w:sdtPr>{pr}</w:sdtPr>\
                     <w:sdtContent>{content}</w:sdtContent></w:sdt>"
                )
                .as_bytes(),
            )
            .unwrap()
        };
        let runs = "<w:p><w:pPr><w:tabs><w:tab w:val=\"left\" w:pos=\"720\"/></w:tabs></w:pPr>\
                    <w:bookmarkStart w:id=\"0\" w:name=\"b\"/><w:r><w:rPr><w:b/></w:rPr><w:t>One</w:t>\
                    <w:tab/><w:t>two</w:t></w:r><w:del><w:r><w:delText>gone</w:delText></w:r></w:del></w:p>";
        let shown_as = |pr: &str, content: &str| shown(&sdt(pr, content));
        assert_eq!(shown_as("<w:text/>", runs).as_deref(), Some("One\ttwo"));
        assert_eq!(
            shown_as("<w:showingPlcHdr/><w:text/>", runs).as_deref(),
            Some("")
        );
        // A date as `w:storeMappedDataAs` asks (dateTime by default).
        let date =
            |mapped: &str| format!("<w:date w:fullDate=\"2015-11-18T00:00:00Z\">{mapped}</w:date>");
        assert_eq!(
            shown_as(&date(""), runs).as_deref(),
            Some("2015-11-18T00:00:00Z")
        );
        assert_eq!(
            shown_as(&date("<w:storeMappedDataAs w:val=\"date\"/>"), runs).as_deref(),
            Some("2015-11-18")
        );
        assert_eq!(
            shown_as(&date("<w:storeMappedDataAs w:val=\"text\"/>"), runs).as_deref(),
            Some("One\ttwo")
        );
        assert_eq!(shown_as("<w:date/>", runs), None);
        // A list holds its chosen item's value.
        let list = |kind: &str| {
            format!(
                "<w:{kind}><w:listItem w:displayText=\"Chosen\" w:value=\"1\"/>\
                 <w:listItem w:value=\"Other\"/></w:{kind}>"
            )
        };
        let chosen = "<w:r><w:t>Chosen</w:t></w:r>";
        assert_eq!(
            shown_as(&list("dropDownList"), chosen).as_deref(),
            Some("1")
        );
        let typed = "<w:r><w:t>typed</w:t></w:r>";
        assert_eq!(shown_as(&list("dropDownList"), typed), None);
        assert_eq!(shown_as(&list("comboBox"), typed).as_deref(), Some("typed"));
        assert_eq!(
            shown_as(&list("comboBox"), "<w:r><w:t>Other</w:t></w:r>").as_deref(),
            Some("Other")
        );
        // Controls whose store value is not their text, and content plain
        // text cannot hold.
        for (pr, content) in [
            ("", runs),
            ("<w:richText/>", runs),
            ("<w:picture/>", runs),
            (
                "<w14:checkbox><w14:checked w14:val=\"1\"/></w14:checkbox>",
                runs,
            ),
            ("<w:text/>", "<w:p><w:r><w:t>a</w:t></w:r></w:p><w:p/>"),
            (
                "<w:text/>",
                "<w:r><w:fldChar w:fldCharType=\"begin\"/></w:r>",
            ),
            (
                "<w:text/>",
                "<w:r><w:sym w:font=\"Symbol\" w:char=\"F0B7\"/></w:r>",
            ),
            ("<w:text/>", "<w:r><w:drawing><w:x/></w:drawing></w:r>"),
        ] {
            assert_eq!(shown_as(pr, content), None, "{pr} {content}");
        }
        // A multi-line control's break is a line feed.
        assert_eq!(
            shown_as(
                "<w:text w:multiLine=\"1\"/>",
                "<w:r><w:t>a</w:t><w:br/><w:t>b</w:t></w:r>"
            )
            .as_deref(),
            Some("a\nb")
        );
    }

    #[test]
    fn an_unbuilt_binding_is_dropped_and_no_other() {
        let xml = "<w:sdtPr><w:dataBinding w:prefixMappings=\"xmlns:ns0=&apos;urn:a&apos;\" w:xpath=\"/ns0:a[1]/@ns0:b\" w:storeItemID=\"{AB}\"/><w:text/></w:sdtPr>\
                   <w:sdtPr><w:dataBinding w:xpath=\"/ns0:a[1]\" w:storeItemID=\"{AB}\"/></w:sdtPr>";
        assert_eq!(
            unbound(xml, "{ab}", "/ns0:a[1]/@ns0:b"),
            "<w:sdtPr><w:text/></w:sdtPr>\
             <w:sdtPr><w:dataBinding w:xpath=\"/ns0:a[1]\" w:storeItemID=\"{AB}\"/></w:sdtPr>"
        );
    }

    #[test]
    fn a_binding_is_dropped_however_its_tag_is_written() {
        // Single quotes, an entity in the path, an element closed by its
        // own end tag, and the word in text: only the two bindings go.
        let xml = "<w:p><w:t>dataBinding</w:t></w:p>\
                   <w:sdtPr><w:dataBinding w:xpath='/ns0:a[1]/ns0:b[2]' w:storeItemID='{AB}'/><w:text/></w:sdtPr>\
                   <w:sdtPr><w:dataBinding w:xpath=\"/ns0:a[1]/ns0:b[2]\" w:storeItemID=\"{AB}\"></w:dataBinding><w:text/></w:sdtPr>\
                   <w:sdtPr><w:dataBinding w:xpath=\"/ns0:a[1]/ns0:b[&#50;]\" w:storeItemID=\"{CD}\"/></w:sdtPr>";
        assert_eq!(
            unbound(xml, "{ab}", "/ns0:a[1]/ns0:b[2]"),
            "<w:p><w:t>dataBinding</w:t></w:p>\
             <w:sdtPr><w:text/></w:sdtPr>\
             <w:sdtPr><w:text/></w:sdtPr>\
             <w:sdtPr><w:dataBinding w:xpath=\"/ns0:a[1]/ns0:b[&#50;]\" w:storeItemID=\"{CD}\"/></w:sdtPr>"
        );
        assert_eq!(
            unbound(xml, "{CD}", "/ns0:a[1]/ns0:b[2]"),
            "<w:p><w:t>dataBinding</w:t></w:p>\
             <w:sdtPr><w:dataBinding w:xpath='/ns0:a[1]/ns0:b[2]' w:storeItemID='{AB}'/><w:text/></w:sdtPr>\
             <w:sdtPr><w:dataBinding w:xpath=\"/ns0:a[1]/ns0:b[2]\" w:storeItemID=\"{AB}\"></w:dataBinding><w:text/></w:sdtPr>\
             <w:sdtPr></w:sdtPr>"
        );
    }

    #[test]
    fn a_node_bound_whole_and_in_parts_keeps_its_parts() {
        // A repeating section binds its item, then the item's fields.
        let node = |local: &str| ("urn:r".to_string(), local.to_string());
        let whole = [node("root"), node("item")];
        let part = [node("root"), node("item"), node("name")];
        let expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\
             <root xmlns=\"urn:r\"><item><name>Ann</name></item></root>";
        // Either order holds the parts.
        for order in [[&whole[..], &part[..]], [&part[..], &whole[..]]] {
            let mut root = Node {
                namespace: "urn:r".to_string(),
                local: "root".to_string(),
                value: None,
                children: Vec::new(),
            };
            for steps in order {
                let value = if steps.len() == 2 { "Ann 3" } else { "Ann" };
                assert!(matches!(insert(&mut root, steps, value), Placed::Yes));
            }
            assert_eq!(store_xml(&root), expected);
        }
    }
}