jubarte-edit 0.20.0

The edit product of the jubarte engine: edit plans as tracked changes, text diff views, capabilities and staged publication
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
//
// SPDX-License-Identifier: Apache-2.0

//! `fill_control`: write a value into one content control (`w:sdt`) of the
//! body. The control is found by id, tag or alias; its `w:sdtPr` survives
//! (only `w:showingPlcHdr` goes, as when a person types into it) and its
//! `w:sdtContent` is replaced by one run, or one paragraph for a block-level
//! control.
//!
//! Backs the `fill_control` plan operation: [`ControlSelector`] is its
//! `control` field, and exactly one of `text`, `choice`, `checked`, `date`
//! names the value.

use serde::{Deserialize, Serialize};

use super::tracked::{COMMENT_RANGE_END, RANGE_ENDS, RANGE_STARTS};
use super::{
    EditError, EditOutcome, ExistingRevisions, Resolution, Resolved, Transaction, check_text, err,
    excerpt,
};
use crate::namespaces::{W, W14};
use crate::xmllinq::{Dom, NodeId, XNamespace};

/// Which content control to fill; every form must match exactly one.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(untagged, deny_unknown_fields)]
pub enum ControlSelector {
    /// `"p3.cc0"` or `"cc1"`, the same as `{"id": "p3.cc0"}`.
    Name(String),
    /// `{"id": "p3.cc0"}`.
    Id {
        /// `ccN` (a block control) or `pN.ccK` (one in paragraph `pN`)
        /// from `inspect`'s `controls`.
        id: String,
    },
    /// `{"tag": "Name"}`: the control's `w:tag`.
    Tag {
        /// The tag, matched exactly.
        tag: String,
    },
    /// `{"alias": "Full name"}`: the control's `w:alias` (its title).
    Alias {
        /// The alias, matched exactly.
        alias: String,
    },
}

/// What a resolved fill writes.
#[derive(Clone, Debug)]
#[doc(hidden)]
pub enum FillValue {
    /// Plain text (a `text` value or a choice's display text).
    Text(String),
    /// A checkbox state and the glyph that shows it.
    Checked { on: bool, glyph: char, font: String },
    /// `w:fullDate` and the text in the control's date format.
    Date { full: String, text: String },
}

/// The value fields of a `fill_control` operation.
pub(super) struct FillRequest<'a> {
    pub(super) control: &'a ControlSelector,
    pub(super) text: Option<&'a str>,
    pub(super) choice: Option<&'a str>,
    pub(super) checked: Option<bool>,
    pub(super) date: Option<&'a str>,
}

/// Kinds a fill cannot write.
const UNFILLABLE: &[&str] = &["picture", "group", "repeating", "building_block"];

impl Transaction<'_> {
    pub(super) fn resolve_fill_control(
        &self,
        id: &str,
        request: &FillRequest<'_>,
    ) -> Resolution<Vec<Resolved>> {
        let mut outcome = EditOutcome {
            id: id.to_string(),
            kind: String::new(),
            status: String::new(),
            paragraph: None,
            matches: 0,
            context: None,
            comment_id: None,
            code: None,
            message: None,
            anchor_given: None,
            anchor_read_as: None,
            near: None,
            candidates: Vec::new(),
        };
        let fail = |code: &str, msg: String, outcome: EditOutcome| {
            Box::new((err(code, Some(id), msg), outcome))
        };
        let control = match self.select_control(request.control) {
            Ok(n) => n,
            Err((code, msg, matches)) => {
                outcome.matches = matches;
                return Err(fail(code, msg, outcome));
            }
        };
        let record = &self.control_records[control];
        outcome.matches = 1;
        outcome.paragraph = record.paragraph_ids.first().cloned();
        let dom = &self.opened.dom;
        let sdt = self.controls[control];
        if self.plan.existing_revisions == ExistingRevisions::Keep {
            return Err(fail(
                "UNSUPPORTED_STRUCTURE",
                "fill_control is not emitted as tracked changes under existing_revisions \"keep\" yet; accept or reject the existing revisions first".into(),
                outcome,
            ));
        }
        if record.locked {
            return Err(fail(
                "LOCKED_CONTROL",
                format!("{} is locked against editing (w:lock)", record.id),
                outcome,
            ));
        }
        if UNFILLABLE.contains(&record.kind.as_str()) {
            return Err(fail(
                "UNSUPPORTED_STRUCTURE",
                format!(
                    "{} is a {} control, which fill_control cannot write",
                    record.id, record.kind
                ),
                outcome,
            ));
        }
        let content = dom.element(sdt, &W::sdt_content());
        let block = dom.ancestors(sdt, Some(&W::p())).is_empty();
        if let Some(content) = content
            && dom.elements(content, None).into_iter().any(|c| {
                [W::tr(), W::tc(), W::tbl()]
                    .iter()
                    .any(|n| dom.name_is(c, n))
            })
        {
            return Err(fail(
                "UNSUPPORTED_STRUCTURE",
                format!("{} holds table rows, cells or tables", record.id),
                outcome,
            ));
        }
        if let Some(content) = content
            && ["footnoteReference", "endnoteReference", "commentReference"]
                .iter()
                .any(|r| !dom.descendants(content, Some(&W::name(r))).is_empty())
        {
            return Err(fail(
                "UNSUPPORTED_STRUCTURE",
                format!(
                    "{} holds a footnote, endnote or comment reference the fill would remove",
                    record.id
                ),
                outcome,
            ));
        }
        if block && content.is_some_and(|c| !dom.descendants(c, Some(&W::sect_pr())).is_empty()) {
            return Err(fail(
                "UNSUPPORTED_STRUCTURE",
                format!("{} holds a section break", record.id),
                outcome,
            ));
        }
        let value = match self.fill_value(record, sdt, request) {
            Ok(value) => value,
            Err(msg) => return Err(fail("INVALID_EDIT", msg, outcome)),
        };
        let new_text = match &value {
            FillValue::Text(text) | FillValue::Date { text, .. } => text.clone(),
            FillValue::Checked { glyph, .. } => glyph.to_string(),
        };
        outcome.context = Some(format!(
            "{{⌷ {} \"{}\"→\"{}\"}}",
            record.id,
            excerpt(&record.text, 40),
            excerpt(&new_text, 40)
        ));
        let paragraphs = self
            .paragraph_nodes
            .iter()
            .enumerate()
            .filter(|&(g, _)| {
                let (story, local) = self.paragraph_story[g];
                story == 0
                    && record
                        .paragraph_ids
                        .iter()
                        .any(|p| p == &crate::ids::paragraph_id("body", local))
            })
            .map(|(g, _)| g)
            .collect();
        Ok((
            vec![Resolved::FillControl {
                control,
                paragraphs,
                block,
                value,
            }],
            outcome,
        ))
    }

    /// The control index, or `(code, message, matches)`.
    fn select_control(
        &self,
        selector: &ControlSelector,
    ) -> Result<usize, (&'static str, String, usize)> {
        let records = &self.control_records;
        let origin = self.origin.as_ref();
        // Ids are the source's: once the plan's revisions are settled, a
        // control id names the source control the author read.
        let ids: Vec<&str> = match origin {
            Some(origin) => origin.control_ids().iter().map(String::as_str).collect(),
            None => records.iter().map(|r| r.id.as_str()).collect(),
        };
        let name_of = |n: usize| -> &str {
            origin
                .and_then(|o| o.control_source(n))
                .unwrap_or(records[n].id.as_str())
        };
        let (what, hits): (String, Vec<usize>) = match selector {
            ControlSelector::Name(given) | ControlSelector::Id { id: given } => {
                if let Some(refused) = super::origin::source_only(given) {
                    return Err(("ANCHOR_NOT_FOUND", refused, 0));
                }
                // The spec's cell spelling `t0.row1.cell2.cc0` names a
                // control of the cell's first paragraph, `p40.cc0`.
                let spelled = self.cell_control(given);
                let id = spelled.as_ref().unwrap_or(given);
                match origin {
                    Some(origin) => match origin.control(id) {
                        Some(Ok(n)) => return Ok(n),
                        Some(Err(gone)) => return Err(("ANCHOR_NOT_FOUND", gone, 0)),
                        None => {}
                    },
                    None => {
                        if let Some(n) = ids.iter().position(|c| c == id) {
                            return Ok(n);
                        }
                    }
                }
                // The expired `body:sdt:N` names the Nth control: refused,
                // with the id it now has.
                let settled = id
                    .strip_prefix("body:sdt:")
                    .and_then(|n| n.parse::<usize>().ok())
                    .and_then(|n| ids.get(n))
                    .map(|c| format!("; the settled spelling is {c}"))
                    .unwrap_or_default();
                let known = match ids.as_slice() {
                    [] => "the body has none".to_string(),
                    [only] => format!("the body has {only}"),
                    [first, .., last] => {
                        format!("the body has {} (first {first}, last {last})", ids.len())
                    }
                };
                return Err((
                    "ANCHOR_NOT_FOUND",
                    format!("no content control {given:?}; {known}{settled}"),
                    0,
                ));
            }
            ControlSelector::Tag { tag } => (
                format!("tag {tag:?}"),
                (0..records.len())
                    .filter(|&n| records[n].tag.as_deref() == Some(tag))
                    .collect(),
            ),
            ControlSelector::Alias { alias } => (
                format!("alias {alias:?}"),
                (0..records.len())
                    .filter(|&n| records[n].alias.as_deref() == Some(alias))
                    .collect(),
            ),
        };
        match hits.as_slice() {
            [n] => Ok(*n),
            [] => Err((
                "ANCHOR_NOT_FOUND",
                format!("no content control has {what}"),
                0,
            )),
            many => Err((
                "AMBIGUOUS_ANCHOR",
                format!(
                    "{} content controls have {what}: {}; select one by id",
                    many.len(),
                    many.iter()
                        .map(|&n| name_of(n))
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
                many.len(),
            )),
        }
    }

    /// `t0.row1.cell2[.pK].ccN` as the `pM.ccN` of the paragraph its
    /// cell spelling names; `None` for any other id.
    fn cell_control(&self, id: &str) -> Option<String> {
        let (paragraph, n) = id.rsplit_once(".cc")?;
        n.parse::<usize>().ok()?;
        if !paragraph.starts_with('t') {
            return None;
        }
        let ids = match &self.origin {
            Some(origin) => origin.ids(),
            None => self.ids(),
        };
        let p = ids.paragraph_id(paragraph)?.ok()?;
        Some(format!("{p}.cc{n}"))
    }

    /// Check the value form against the control and compute what to write.
    fn fill_value(
        &self,
        record: &crate::inspect::ContentControl,
        sdt: NodeId,
        request: &FillRequest<'_>,
    ) -> Result<FillValue, String> {
        let dom = &self.opened.dom;
        let given = [
            request.text.is_some(),
            request.choice.is_some(),
            request.checked.is_some(),
            request.date.is_some(),
        ]
        .iter()
        .filter(|&&g| g)
        .count();
        if given != 1 {
            return Err(format!(
                "fill_control takes exactly one of text, choice, checked, date (got {given})"
            ));
        }
        let kind = record.kind.as_str();
        let form_for = |kind: &str| match kind {
            "drop_down" => "choice",
            "checkbox" => "checked",
            "date" => "date",
            _ => "text",
        };
        let wrong = |form: &str| {
            format!(
                "{} is a {kind} control; fill it with {}, not {form}",
                record.id,
                form_for(kind)
            )
        };
        let pr = dom.element(sdt, &W::sdt_pr());
        if let Some(text) = request.text {
            if matches!(kind, "drop_down" | "checkbox" | "date") {
                return Err(wrong("text"));
            }
            check_text(text)?;
            return Ok(FillValue::Text(text.to_string()));
        }
        if let Some(choice) = request.choice {
            if !matches!(kind, "drop_down" | "combo_box") {
                return Err(wrong("choice"));
            }
            let list = pr.and_then(|pr| {
                dom.element(pr, &W::name("dropDownList"))
                    .or_else(|| dom.element(pr, &W::name("comboBox")))
            });
            let items = list.map_or_else(Vec::new, |l| dom.elements(l, Some(&W::name("listItem"))));
            for item in items {
                let value = dom.attribute(item, &W::name("value"));
                let display = dom.attribute(item, &W::name("displayText"));
                if value == Some(choice) || display == Some(choice) {
                    let shown = display.or(value).unwrap_or(choice);
                    return Ok(FillValue::Text(shown.to_string()));
                }
            }
            return Err(format!(
                "choice {choice:?} is not one of {} for {}",
                record.choices.join(", "),
                record.id
            ));
        }
        if let Some(on) = request.checked {
            if kind != "checkbox" {
                return Err(wrong("checked"));
            }
            let checkbox = pr.and_then(|pr| dom.element(pr, &W14::name("checkbox")));
            let state = checkbox.and_then(|c| {
                dom.element(
                    c,
                    &W14::name(if on { "checkedState" } else { "uncheckedState" }),
                )
            });
            let glyph = state
                .and_then(|s| dom.attribute(s, &W14::name("val")))
                .and_then(|v| u32::from_str_radix(v, 16).ok())
                .and_then(char::from_u32)
                .filter(|c| !c.is_control())
                .unwrap_or(if on { '\u{2612}' } else { '\u{2610}' });
            let font = state
                .and_then(|s| dom.attribute(s, &W14::name("font")))
                .unwrap_or("MS Gothic")
                .to_string();
            return Ok(FillValue::Checked { on, glyph, font });
        }
        let date = request.date.unwrap_or_default();
        if kind != "date" {
            return Err(wrong("date"));
        }
        let (y, m, d) = parse_date(date)
            .ok_or_else(|| format!("date {date:?} is not a calendar date in YYYY-MM-DD form"))?;
        let pattern = pr
            .and_then(|pr| dom.element(pr, &W::date()))
            .and_then(|e| dom.element(e, &W::name("dateFormat")))
            .and_then(|f| dom.attribute(f, &W::val()))
            .unwrap_or("yyyy-MM-dd");
        Ok(FillValue::Date {
            full: format!("{date}T00:00:00Z"),
            text: format_date(pattern, y, m, d),
        })
    }

    /// Fills against each other and against paragraph operations.
    pub(super) fn check_control_conflicts(&self, deleted: &[usize]) -> Result<(), EditError> {
        let dom = &self.opened.dom;
        let fills: Vec<(usize, usize, &Vec<usize>, bool)> = self
            .resolved
            .iter()
            .filter_map(|(i, r)| match r {
                Resolved::FillControl {
                    control,
                    paragraphs,
                    block,
                    ..
                } => Some((*i, *control, paragraphs, *block)),
                _ => None,
            })
            .collect();
        for (k, &(i, control, _, _)) in fills.iter().enumerate() {
            for &(_, other, _, _) in &fills[..k] {
                if other == control {
                    return Err(self.conflict(i, "fills a control another operation fills"));
                }
                let (a, b) = (self.controls[control], self.controls[other]);
                if dom.ancestors(a, None).contains(&b) || dom.ancestors(b, None).contains(&a) {
                    return Err(
                        self.conflict(i, "fills a control nested in another filled control")
                    );
                }
            }
        }
        for &(i, _, paragraphs, block) in &fills {
            for (j, r) in &self.resolved {
                let touched: Vec<usize> = match r {
                    Resolved::Text { para, .. }
                    | Resolved::CommentRange { para, .. }
                    | Resolved::FormatParagraph { para, .. }
                        if block =>
                    {
                        vec![*para]
                    }
                    Resolved::InsertParagraph { anchor, like, .. } if block => {
                        vec![*anchor, *like]
                    }
                    Resolved::InsertTable { anchor, .. } if block => vec![*anchor],
                    Resolved::List { paras, .. } if block => paras.clone(),
                    Resolved::CommentSpan { para, last, .. } if block => (*para..=*last).collect(),
                    Resolved::MergeParagraphs { para, next, .. } => vec![*para, *next],
                    _ => Vec::new(),
                };
                if touched.iter().any(|p| paragraphs.contains(p)) {
                    return Err(self.conflict(
                        i.max(*j),
                        "fills a control whose paragraph another operation changes",
                    ));
                }
            }
            if paragraphs.iter().any(|p| deleted.contains(p)) {
                return Err(self.conflict(i, "fills a control in a deleted paragraph"));
            }
        }
        Ok(())
    }

    /// Apply step 1b: write every fill. Text edits (step 1) never touch
    /// content-control runs, so the controls' nodes are still in place.
    pub(super) fn apply_fills(&mut self) {
        let fills: Vec<(usize, bool, FillValue)> = self
            .resolved
            .iter()
            .filter_map(|(_, r)| match r {
                Resolved::FillControl {
                    control,
                    block,
                    value,
                    ..
                } => Some((*control, *block, value.clone())),
                _ => None,
            })
            .collect();
        for (control, block, value) in fills {
            fill(&mut self.opened.dom, self.controls[control], block, &value);
        }
    }
}

/// Write `value` into the control `sdt`.
fn fill(dom: &mut Dom, sdt: NodeId, block: bool, value: &FillValue) {
    let pr = match dom.element(sdt, &W::sdt_pr()) {
        Some(pr) => pr,
        None => {
            let pr = dom.new_element(W::sdt_pr());
            dom.add_first(sdt, pr);
            pr
        }
    };
    if let Some(plc) = dom.element(pr, &W::name("showingPlcHdr")) {
        dom.remove(plc);
    }
    let content = match dom.element(sdt, &W::sdt_content()) {
        Some(content) => content,
        None => {
            let content = dom.new_element(W::sdt_content());
            dom.add(sdt, content);
            content
        }
    };
    let rpr = first_run_properties(dom, content);
    let text = match value {
        FillValue::Text(text) => text.clone(),
        FillValue::Date { full, text } => {
            if let Some(date) = dom.element(pr, &W::date()) {
                dom.set_attribute_value(date, &W::name("fullDate"), Some(full));
            }
            text.clone()
        }
        FillValue::Checked { on, glyph, font } => {
            if let Some(checkbox) = dom.element(pr, &W14::name("checkbox")) {
                let checked = match dom.element(checkbox, &W14::name("checked")) {
                    Some(checked) => checked,
                    None => {
                        let checked = dom.new_element(W14::name("checked"));
                        dom.add_first(checkbox, checked);
                        checked
                    }
                };
                dom.set_attribute_value(
                    checked,
                    &W14::name("val"),
                    Some(if *on { "1" } else { "0" }),
                );
            }
            let rpr = rpr.unwrap_or_else(|| dom.new_element(W::r_pr()));
            set_glyph_font(dom, rpr, font);
            return write_content(dom, content, block, Some(rpr), &glyph.to_string());
        }
    };
    write_content(dom, content, block, rpr, &text);
}

/// The range markers under `content`, detached: `(starts, ends)` in
/// document order. A fill puts the starts before its new run and the ends
/// after it, so bookmarks, comment ranges, permissions and move ranges keep
/// both halves: the markers an insertion beside them reads (#1156).
fn take_range_markers(dom: &mut Dom, content: NodeId) -> (Vec<NodeId>, Vec<NodeId>) {
    let (mut starts, mut ends) = (Vec::new(), Vec::new());
    for node in dom.descendants(content, None) {
        let Some(name) = dom.name(node) else { continue };
        if name.namespace_name() != W::URI {
            continue;
        }
        if RANGE_STARTS.contains(&name.local_name()) {
            starts.push(node);
        } else if RANGE_ENDS.contains(&name.local_name()) || name.local_name() == COMMENT_RANGE_END
        {
            ends.push(node);
        }
    }
    for &node in starts.iter().chain(&ends) {
        dom.remove(node);
    }
    (starts, ends)
}

/// Replace `content`'s children with one run (or one paragraph holding it,
/// keeping the first paragraph's properties, for a block-level control).
/// Range markers inside the old content surround the new run.
fn write_content(dom: &mut Dom, content: NodeId, block: bool, rpr: Option<NodeId>, text: &str) {
    let (starts, ends) = take_range_markers(dom, content);
    let r = dom.new_element(W::r());
    if let Some(rpr) = rpr
        && !dom.elements(rpr, None).is_empty()
    {
        dom.add(r, rpr);
    }
    let t = dom.new_element(W::t());
    dom.set_attribute_value(t, &XNamespace::xml().name("space"), Some("preserve"));
    dom.add_text(t, text);
    dom.add(r, t);
    let ppr = dom
        .descendants(content, Some(&W::p()))
        .first()
        .and_then(|&first| dom.element(first, &W::p_pr()))
        .map(|ppr| dom.clone_subtree(ppr));
    dom.remove_nodes(content);
    let holder = if block {
        let p = dom.new_element(W::p());
        if let Some(ppr) = ppr {
            for child in dom.elements(ppr, None) {
                if dom.name_is(child, &W::p_pr_change()) || dom.name_is(child, &W::sect_pr()) {
                    dom.remove(child);
                }
            }
            dom.add(p, ppr);
        }
        dom.add(content, p);
        p
    } else {
        content
    };
    for node in starts.into_iter().chain([r]).chain(ends) {
        dom.add(holder, node);
    }
}

/// A copy of the first run's properties in `content`, without the
/// placeholder style and revision marks.
fn first_run_properties(dom: &mut Dom, content: NodeId) -> Option<NodeId> {
    let source = dom
        .descendants(content, Some(&W::r()))
        .into_iter()
        .find_map(|r| dom.element(r, &W::r_pr()))?;
    let rpr = dom.clone_subtree(source);
    for child in dom.elements(rpr, None) {
        let placeholder = dom.name_is(child, &W::name("rStyle"))
            && dom.attribute(child, &W::val()) == Some("PlaceholderText");
        if placeholder
            || dom.name_is(child, &W::r_pr_change())
            || dom.name_is(child, &W::ins())
            || dom.name_is(child, &W::del())
        {
            dom.remove(child);
        }
    }
    Some(rpr)
}

/// Point every script's font at `font`, as Word does for a checkbox glyph.
fn set_glyph_font(dom: &mut Dom, rpr: NodeId, font: &str) {
    let fonts = match dom.element(rpr, &W::name("rFonts")) {
        Some(fonts) => fonts,
        None => {
            let fonts = dom.new_element(W::name("rFonts"));
            super::insert_rpr_child(dom, rpr, fonts);
            fonts
        }
    };
    for slot in ["ascii", "hAnsi", "eastAsia", "cs"] {
        dom.set_attribute_value(fonts, &W::name(slot), Some(font));
    }
    dom.set_attribute_value(fonts, &W::name("hint"), Some("eastAsia"));
}

/// `YYYY-MM-DD` with a real calendar day.
fn parse_date(date: &str) -> Option<(i32, u32, u32)> {
    let bytes = date.as_bytes();
    if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
        return None;
    }
    let digits = |s: &str| -> Option<u32> {
        s.bytes()
            .all(|b| b.is_ascii_digit())
            .then(|| s.parse().ok())?
    };
    let y = i32::try_from(digits(&date[..4])?).ok()?;
    let m = digits(&date[5..7])?;
    let d = digits(&date[8..])?;
    ((1..=12).contains(&m) && (1..=days_in_month(y, m)).contains(&d)).then_some((y, m, d))
}

fn days_in_month(y: i32, m: u32) -> u32 {
    match m {
        2 if (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 => 29,
        2 => 28,
        4 | 6 | 9 | 11 => 30,
        _ => 31,
    }
}

/// Day of the week, 0 = Sunday (Sakamoto's method).
fn weekday(y: i32, m: u32, d: u32) -> usize {
    const T: [i32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
    let y = if m < 3 { y - 1 } else { y };
    let w = y + y / 4 - y / 100 + y / 400 + T[m as usize - 1] + d as i32;
    w.rem_euclid(7) as usize
}

const MONTHS: [&str; 12] = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
];
const DAYS: [&str; 7] = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
];

/// Format a date with a Word date pattern (`yyyy`, `yy`, `MMMM`, `MMM`,
/// `MM`, `M`, `dddd`, `ddd`, `dd`, `d`; `'quoted'` text is literal; other
/// characters are copied). Names are English; `w:lid` is not consulted.
fn format_date(pattern: &str, y: i32, m: u32, d: u32) -> String {
    let chars: Vec<char> = pattern.chars().collect();
    let mut out = String::new();
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if c == '\'' {
            let close = chars[i + 1..].iter().position(|&q| q == '\'');
            let end = close.map_or(chars.len(), |p| i + 1 + p);
            out.extend(&chars[i + 1..end]);
            i = end + 1;
            continue;
        }
        let run = chars[i..].iter().take_while(|&&x| x == c).count();
        match c {
            'y' => {
                if run >= 3 {
                    out.push_str(&format!("{y:04}"));
                } else {
                    out.push_str(&format!("{:02}", y.rem_euclid(100)));
                }
            }
            'M' => match run {
                1 => out.push_str(&m.to_string()),
                2 => out.push_str(&format!("{m:02}")),
                3 => out.push_str(&MONTHS[m as usize - 1][..3]),
                _ => out.push_str(MONTHS[m as usize - 1]),
            },
            'd' => match run {
                1 => out.push_str(&d.to_string()),
                2 => out.push_str(&format!("{d:02}")),
                3 => out.push_str(&DAYS[weekday(y, m, d)][..3]),
                _ => out.push_str(DAYS[weekday(y, m, d)]),
            },
            _ => out.extend(std::iter::repeat_n(c, run)),
        }
        i += run;
    }
    out
}

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

    #[test]
    fn dates_parse_only_real_days() {
        assert_eq!(parse_date("2024-02-29"), Some((2024, 2, 29)));
        assert_eq!(parse_date("2000-02-29"), Some((2000, 2, 29)));
        for bad in [
            "2023-02-29",
            "1900-02-29",
            "2026-13-01",
            "2026-00-10",
            "2026-04-31",
            "2026-1-01",
            "2026/10/02",
            "+026-10-02",
            "abcd-10-02",
        ] {
            assert_eq!(parse_date(bad), None, "{bad}");
        }
    }

    #[test]
    fn word_date_patterns_format_in_english() {
        assert_eq!(format_date("yyyy-MM-dd", 2026, 10, 2), "2026-10-02");
        assert_eq!(format_date("d MMMM yyyy", 2027, 1, 5), "5 January 2027");
        assert_eq!(format_date("M/d/yy", 2026, 3, 9), "3/9/26");
        assert_eq!(format_date("dddd, MMM dd", 2026, 10, 2), "Friday, Oct 02");
        assert_eq!(format_date("ddd 'the' d", 2026, 10, 4), "Sun the 4");
        assert_eq!(format_date("'open", 2026, 10, 4), "open");
        assert_eq!(format_date("yyyy.MM", 2026, 10, 4), "2026.10");
    }
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod control_source_boundary_tests {
    use super::*;
    use crate::edit::{EditPlan, apply_plan, preview_plan};
    use crate::opc::PartFs;
    fn parse(body: &str) -> (Dom, NodeId) {
        let mut dom = Dom::new();
        let document = dom.parse_xdocument(&format!("<w:document xmlns:w='{}' xmlns:w14='{}'><w:body>{body}<w:sectPr><w:pgSz w:w='12240' w:h='15840'/></w:sectPr></w:body></w:document>",W::URI,W14::URI));
        let root = dom.root(document).unwrap();
        (dom, root)
    }
    fn package(body: &str) -> Vec<u8> {
        let (dom, root) = parse(body);
        let mut pkg = PartFs::open(include_bytes!(
            "../../../../tests/fixtures/word_probes/tokens/cell_a.docx"
        ))
        .unwrap();
        pkg.set_part(
            "word/document.xml",
            dom.serialize_element(root).into_bytes(),
        );
        pkg.to_zip().unwrap()
    }
    fn plan(operations: &str) -> EditPlan {
        EditPlan::from_json(&format!(r#"{{"schema_version":1,"author":"Editor","date":"2001-02-03T04:05:06Z","operations":[{operations}]}}"#)).unwrap()
    }
    #[test]
    fn filling_empty_authored_controls_creates_only_missing_metadata_and_payload() {
        for block in [false, true] {
            for properties in [false, true] {
                for content in [false, true] {
                    let props = if properties {
                        "<w:sdtPr><w:alias w:val='Clause'/><w:tag w:val='stable-clause'/><w:id w:val='31'/><w:richText/></w:sdtPr>"
                    } else {
                        ""
                    };
                    let content = if content { "<w:sdtContent/>" } else { "" };
                    let sdt = format!("<w:sdt>{props}{content}</w:sdt>");
                    let body = if block {
                        sdt
                    } else {
                        format!("<w:p>{sdt}</w:p>")
                    };
                    let (mut dom, root) = parse(&body);
                    let sdt = dom.descendants(root, Some(&W::sdt()))[0];
                    let parent = dom.parent(sdt);
                    let metadata = dom
                        .element(sdt, &W::sdt_pr())
                        .map(|pr| dom.serialize_element(pr));
                    fill(&mut dom, sdt, block, &FillValue::Text("new clause".into()));
                    assert_eq!(dom.parent(sdt), parent);
                    let pr = dom.element(sdt, &W::sdt_pr()).unwrap();
                    assert_eq!(dom.elements(sdt, Some(&W::sdt_pr())).len(), 1);
                    if let Some(metadata) = metadata {
                        assert_eq!(dom.serialize_element(pr), metadata);
                    } else {
                        assert!(dom.elements(pr, None).is_empty());
                    }
                    let content = dom.element(sdt, &W::sdt_content()).unwrap();
                    assert_eq!(dom.elements(sdt, Some(&W::sdt_content())).len(), 1);
                    let holder = if block {
                        assert_eq!(dom.elements(content, None).len(), 1);
                        dom.element(content, &W::p()).unwrap()
                    } else {
                        content
                    };
                    let runs = dom.elements(holder, Some(&W::r()));
                    assert_eq!(runs.len(), 1);
                    assert!(dom.element(runs[0], &W::r_pr()).is_none());
                    let text = dom.element(runs[0], &W::t()).unwrap();
                    assert_eq!(dom.value(text), "new clause");
                    assert_eq!(
                        dom.attribute(text, &XNamespace::xml().name("space")),
                        Some("preserve")
                    );
                    assert_eq!(dom.value(root), "new clause");
                }
            }
        }
    }
    #[test]
    fn public_block_controls_refuse_section_loss_and_both_nested_fill_orders() {
        let content = "<w:sdt><w:sdtPr><w:tag w:val='Section'/><w:richText/></w:sdtPr><w:sdtContent><w:p><w:pPr><w:sectPr><w:pgSz w:w='10000' w:h='14000'/></w:sectPr></w:pPr><w:r><w:t>owned section</w:t></w:r></w:p></w:sdtContent></w:sdt><w:p><w:r><w:t>independent tail</w:t></w:r></w:p>";
        let source = package(content);
        let operation =
            plan(r#"{"kind":"fill_control","control":{"tag":"Section"},"text":"replacement"}"#);
        assert_eq!(
            apply_plan(&source, &operation).unwrap_err().code,
            "UNSUPPORTED_STRUCTURE"
        );
        assert_eq!(
            preview_plan(&source, &operation).unwrap_err().code,
            "UNSUPPORTED_STRUCTURE"
        );
        let nested = "<w:sdt><w:sdtPr><w:tag w:val='Outer'/><w:richText/></w:sdtPr><w:sdtContent><w:p><w:sdt><w:sdtPr><w:tag w:val='Inner'/><w:text/></w:sdtPr><w:sdtContent><w:r><w:t>owned nested clause</w:t></w:r></w:sdtContent></w:sdt></w:p></w:sdtContent></w:sdt><w:p/>";
        let source = package(nested);
        for first in ["Outer", "Inner"] {
            let second = if first == "Outer" { "Inner" } else { "Outer" };
            let operations = plan(&format!(
                r#"{{"kind":"fill_control","control":{{"tag":"{first}"}},"text":"first"}},{{"kind":"fill_control","control":{{"tag":"{second}"}},"text":"second"}}"#
            ));
            assert_eq!(
                apply_plan(&source, &operations).unwrap_err().code,
                "OVERLAPPING_EDITS"
            );
            assert_eq!(
                preview_plan(&source, &operations).unwrap_err().code,
                "OVERLAPPING_EDITS"
            );
        }
        let source_pkg = PartFs::open(&source).unwrap();
        let (dom, root) = parse(nested);
        assert_eq!(
            source_pkg.part_string("word/document.xml").unwrap(),
            dom.serialize_element(root)
        );
    }
}

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

    #[test]
    fn dates_need_the_shape_and_a_real_day() {
        assert_eq!(parse_date("2024-02-29"), Some((2024, 2, 29)));
        assert_eq!(parse_date("2023-02-29"), None);
        assert_eq!(parse_date("2000-02-29"), Some((2000, 2, 29)));
        assert_eq!(parse_date("1900-02-29"), None);
        assert_eq!(parse_date("2026-04-31"), None);
        assert_eq!(parse_date("2026-13-01"), None);
        for bad in [
            "2026-1-01",
            "2026/01/01",
            "2026-01/01",
            "20x6-01-01",
            "2026-01-0x",
        ] {
            assert_eq!(parse_date(bad), None, "{bad}");
        }
    }

    #[test]
    fn weekdays_count_from_sunday() {
        assert_eq!(weekday(2026, 1, 4), 0);
        assert_eq!(weekday(2026, 2, 2), 1);
        assert_eq!(weekday(2026, 11, 18), 3);
        assert_eq!(weekday(2000, 3, 1), 3);
    }

    #[test]
    fn run_properties_drop_the_placeholder_style_and_marks() {
        let mut dom = Dom::new();
        let doc = dom.parse_xdocument(&format!(
            r#"<w:sdtContent xmlns:w="{}"><w:r><w:rPr><w:rStyle w:val="PlaceholderText"/><w:b/><w:rStyle w:val="Strong"/><w:ins w:id="1"/><w:del w:id="2"/><w:rPrChange w:id="3"/></w:rPr><w:t>x</w:t></w:r></w:sdtContent>"#,
            W::URI
        ));
        let content = dom.root(doc).unwrap();
        let rpr = first_run_properties(&mut dom, content).unwrap();
        let kept: Vec<String> = dom
            .elements(rpr, None)
            .into_iter()
            .map(|c| {
                let local = dom.name(c).unwrap().local_name().to_string();
                match dom.attribute(c, &W::val()) {
                    Some(v) => format!("{local}={v}"),
                    None => local,
                }
            })
            .collect();
        assert_eq!(kept, ["b", "rStyle=Strong"]);
        let empty = dom.parse_xdocument(&format!(
            r#"<w:sdtContent xmlns:w="{}"><w:r><w:t>x</w:t></w:r></w:sdtContent>"#,
            W::URI
        ));
        let content = dom.root(empty).unwrap();
        assert_eq!(first_run_properties(&mut dom, content), None);
    }
}