docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and loops
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
//! Lossless WordprocessingML document model.
//!
//! The tree keeps the original markup for every element, so an untouched
//! document can be written back byte for byte. Typed roles give the domain a
//! structural view of the parts it cares about: body, paragraph, run, text,
//! table, row and cell.
//!
//! The model never parses or writes XML. That belongs to the adapter layer.

// Some helpers are consumed by later tickets in the migration. The allow is
// removed in T011 once the pipeline is complete.
#![allow(dead_code)]

pub(crate) mod projection;

/// The structural role of an element.
///
/// Roles are assigned by the parser from the qualified element name. Anything
/// the model does not type is [`Role::Opaque`] and is preserved verbatim.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Role {
    /// The root `w:document` element.
    Document,
    /// The `w:body` element.
    Body,
    /// A `w:p` element.
    Paragraph,
    /// A `w:r` element.
    Run,
    /// A `w:t` element.
    Text,
    /// A `w:tbl` element.
    Table,
    /// A `w:tr` element.
    Row,
    /// A `w:tc` element.
    Cell,
    /// A `w:pPr` element.
    ParagraphProps,
    /// A `w:rPr` element.
    RunProps,
    /// A `w:tblPr` element.
    TableProps,
    /// A `w:tblGrid` element.
    TableGrid,
    /// A `w:trPr` element.
    RowProps,
    /// A `w:tcPr` element.
    CellProps,
    /// A `w:sectPr` element.
    SectionProps,
    /// An element that wraps block level children, such as `w:sdtContent`.
    BlockContainer,
    /// An element that wraps inline level children, such as `w:hyperlink`.
    InlineContainer,
    /// Anything else. Preserved byte for byte.
    Opaque,
}

impl Role {
    /// Whether this role is a block in a block container.
    pub(crate) fn is_block(self) -> bool {
        matches!(self, Role::Paragraph | Role::Table | Role::BlockContainer)
    }

    /// Whether this role holds element properties rather than content.
    pub(crate) fn is_property(self) -> bool {
        matches!(
            self,
            Role::ParagraphProps
                | Role::RunProps
                | Role::TableProps
                | Role::TableGrid
                | Role::RowProps
                | Role::CellProps
                | Role::SectionProps
        )
    }
}

/// A text node.
///
/// `raw` is the original escaped payload exactly as it appeared in the source.
/// `value` is the decoded text. While the node is clean, serialization writes
/// `raw`, so entity spelling and CDATA survive. The only way to change the
/// value is [`TextNode::set_value`], which marks the node dirty, so the two
/// fields cannot drift apart.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextNode {
    raw: Vec<u8>,
    value: String,
    dirty: bool,
    preserve_space: bool,
}

impl TextNode {
    /// Create a clean text node from its original bytes and decoded value.
    pub(crate) fn original(raw: Vec<u8>, value: String) -> Self {
        Self {
            raw,
            value,
            dirty: false,
            preserve_space: false,
        }
    }

    /// Create a dirty text node that will be escaped on write.
    pub(crate) fn generated(value: String) -> Self {
        Self {
            raw: Vec::new(),
            value,
            dirty: true,
            preserve_space: false,
        }
    }

    /// The decoded text.
    pub(crate) fn value(&self) -> &str {
        &self.value
    }

    /// Replace the value. Marks the node dirty.
    pub(crate) fn set_value(&mut self, value: String) {
        self.value = value;
        self.dirty = true;
    }

    /// Whether the node must be escaped on write.
    pub(crate) fn is_dirty(&self) -> bool {
        self.dirty
    }

    /// The original escaped bytes, when the node is clean.
    pub(crate) fn raw(&self) -> &[u8] {
        &self.raw
    }

    /// Whether the serializer should emit `xml:space="preserve"`.
    pub(crate) fn preserve_space(&self) -> bool {
        self.preserve_space
    }

    /// Set the preserve space flag.
    pub(crate) fn set_preserve_space(&mut self, preserve: bool) {
        self.preserve_space = preserve;
    }
}

/// A node in the document tree.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Node {
    /// An element with children.
    Element(Element),
    /// A character data node.
    Text(TextNode),
    /// Verbatim bytes that are not an element, such as a comment or a
    /// processing instruction.
    Raw(Vec<u8>),
}

impl Node {
    /// Borrow the node as an element, if it is one.
    pub(crate) fn as_element(&self) -> Option<&Element> {
        match self {
            Node::Element(element) => Some(element),
            _ => None,
        }
    }

    /// Mutably borrow the node as an element, if it is one.
    pub(crate) fn as_element_mut(&mut self) -> Option<&mut Element> {
        match self {
            Node::Element(element) => Some(element),
            _ => None,
        }
    }

    /// Borrow the node as text, if it is one.
    pub(crate) fn as_text(&self) -> Option<&TextNode> {
        match self {
            Node::Text(text) => Some(text),
            _ => None,
        }
    }

    /// Mutably borrow the node as text, if it is one.
    pub(crate) fn as_text_mut(&mut self) -> Option<&mut TextNode> {
        match self {
            Node::Text(text) => Some(text),
            _ => None,
        }
    }
}

/// An element with its original start and end tags.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Element {
    name: String,
    role: Role,
    raw_start: Vec<u8>,
    raw_end: Vec<u8>,
    self_closing: bool,
    children: Vec<Node>,
}

impl Element {
    /// Build an element from already captured markup.
    pub(crate) fn new(
        name: String,
        role: Role,
        raw_start: Vec<u8>,
        raw_end: Vec<u8>,
        self_closing: bool,
        children: Vec<Node>,
    ) -> Self {
        Self {
            name,
            role,
            raw_start,
            raw_end,
            self_closing,
            children,
        }
    }

    /// Build a self closing element with the given raw start tag.
    pub(crate) fn self_closing(name: String, role: Role, raw_start: Vec<u8>) -> Self {
        Self {
            name,
            role,
            raw_start,
            raw_end: Vec::new(),
            self_closing: true,
            children: Vec::new(),
        }
    }

    /// The qualified element name, for example `w:p`.
    pub(crate) fn name(&self) -> &str {
        &self.name
    }

    /// The structural role.
    pub(crate) fn role(&self) -> Role {
        self.role
    }

    /// The original start tag bytes, including the closing `>`.
    pub(crate) fn raw_start(&self) -> &[u8] {
        &self.raw_start
    }

    /// Replace the original start tag bytes.
    ///
    /// Used when a clone needs a rewritten attribute, such as a bookmark id.
    pub(crate) fn set_raw_start(&mut self, raw_start: Vec<u8>) {
        self.raw_start = raw_start;
    }

    /// The original end tag bytes, empty for a self closing element.
    pub(crate) fn raw_end(&self) -> &[u8] {
        &self.raw_end
    }

    /// Whether the element was written in self closing form.
    pub(crate) fn is_self_closing(&self) -> bool {
        self.self_closing
    }

    /// The child nodes.
    pub(crate) fn children(&self) -> &[Node] {
        &self.children
    }

    /// The child nodes, mutably.
    pub(crate) fn children_mut(&mut self) -> &mut Vec<Node> {
        &mut self.children
    }

    /// Append a child node.
    pub(crate) fn push_child(&mut self, child: Node) {
        self.children.push(child);
    }

    /// Set the original end tag bytes captured by the parser.
    pub(crate) fn set_raw_end(&mut self, raw_end: Vec<u8>) {
        self.raw_end = raw_end;
        self.self_closing = false;
    }

    /// Iterate over element children that act as blocks.
    pub(crate) fn blocks(&self) -> impl Iterator<Item = &Element> {
        self.children
            .iter()
            .filter_map(Node::as_element)
            .filter(|element| element.role.is_block())
    }

    /// Iterate over element children that act as blocks, mutably.
    pub(crate) fn blocks_mut(&mut self) -> impl Iterator<Item = &mut Element> {
        self.children
            .iter_mut()
            .filter_map(Node::as_element_mut)
            .filter(|element| element.role.is_block())
    }

    /// Iterate over `w:tr` children.
    pub(crate) fn rows(&self) -> impl Iterator<Item = &Element> {
        self.children
            .iter()
            .filter_map(Node::as_element)
            .filter(|element| element.role == Role::Row)
    }

    /// Iterate over `w:tr` children, mutably.
    pub(crate) fn rows_mut(&mut self) -> impl Iterator<Item = &mut Element> {
        self.children
            .iter_mut()
            .filter_map(Node::as_element_mut)
            .filter(|element| element.role == Role::Row)
    }

    /// Iterate over `w:tc` children.
    pub(crate) fn cells(&self) -> impl Iterator<Item = &Element> {
        self.children
            .iter()
            .filter_map(Node::as_element)
            .filter(|element| element.role == Role::Cell)
    }

    /// Iterate over `w:tc` children, mutably.
    pub(crate) fn cells_mut(&mut self) -> impl Iterator<Item = &mut Element> {
        self.children
            .iter_mut()
            .filter_map(Node::as_element_mut)
            .filter(|element| element.role == Role::Cell)
    }

    /// Recursively collect every `w:t` element under this element.
    pub(crate) fn text_elements(&self) -> Vec<&Element> {
        let mut out = Vec::new();
        self.collect_text_elements(&mut out);
        out
    }

    fn collect_text_elements<'a>(&'a self, out: &mut Vec<&'a Element>) {
        for child in &self.children {
            if let Node::Element(element) = child {
                if element.role == Role::Text {
                    out.push(element);
                } else {
                    element.collect_text_elements(out);
                }
            }
        }
    }

    /// The concatenated decoded text of every `w:t` descendant.
    ///
    /// When this element is itself a `w:t`, returns its own character data.
    pub(crate) fn text(&self) -> String {
        let mut out = String::new();
        self.collect_text(&mut out);
        out
    }

    /// Every decoded character data node under this element, regardless of the
    /// element it sits in. Used to scan opaque subtrees for template syntax.
    pub(crate) fn all_text(&self) -> String {
        let mut out = String::new();
        self.collect_all_text(&mut out);
        out
    }

    fn collect_all_text(&self, out: &mut String) {
        for child in &self.children {
            match child {
                Node::Text(text) => out.push_str(text.value()),
                Node::Element(element) => element.collect_all_text(out),
                Node::Raw(_) => {}
            }
        }
    }

    fn collect_text(&self, out: &mut String) {
        if self.role == Role::Text {
            for child in &self.children {
                if let Node::Text(text) = child {
                    out.push_str(text.value());
                }
            }
            return;
        }
        for child in &self.children {
            if let Node::Element(element) = child {
                element.collect_text(out);
            }
        }
    }

    /// The index of this element among its parent's blocks, given the parent.
    ///
    /// Returns `None` when the element is not a block child of the parent.
    pub(crate) fn block_index_in(&self, parent: &Element) -> Option<usize> {
        parent
            .blocks()
            .position(|candidate| std::ptr::eq(candidate, self))
    }

    /// The element at a child index path below this element.
    pub(crate) fn at(&self, path: &[usize]) -> Option<&Element> {
        let mut current = self;
        for index in path {
            current = current.children().get(*index)?.as_element()?;
        }
        Some(current)
    }

    /// The element at a child index path below this element, mutably.
    pub(crate) fn at_mut(&mut self, path: &[usize]) -> Option<&mut Element> {
        let mut current = self;
        for index in path {
            current = current.children_mut().get_mut(*index)?.as_element_mut()?;
        }
        Some(current)
    }

    /// The index of this element among its parent's rows, given the parent.
    pub(crate) fn row_index_in(&self, parent: &Element) -> Option<usize> {
        parent
            .rows()
            .position(|candidate| std::ptr::eq(candidate, self))
    }
}

/// A parsed part: prolog, root element and epilogue.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Document {
    prolog: Vec<u8>,
    root: Element,
    epilogue: Vec<u8>,
    word_prefix: String,
}

impl Document {
    /// Build a document from its parts.
    pub(crate) fn new(
        prolog: Vec<u8>,
        root: Element,
        epilogue: Vec<u8>,
        word_prefix: String,
    ) -> Self {
        Self {
            prolog,
            root,
            epilogue,
            word_prefix,
        }
    }

    /// Bytes before the root element, including the XML declaration.
    pub(crate) fn prolog(&self) -> &[u8] {
        &self.prolog
    }

    /// The root element.
    pub(crate) fn root(&self) -> &Element {
        &self.root
    }

    /// The root element, mutably.
    pub(crate) fn root_mut(&mut self) -> &mut Element {
        &mut self.root
    }

    /// Bytes after the root element.
    pub(crate) fn epilogue(&self) -> &[u8] {
        &self.epilogue
    }

    /// The prefix bound to the Word namespace, for example `w`.
    pub(crate) fn word_prefix(&self) -> &str {
        &self.word_prefix
    }

    /// The `w:body` element, if present.
    pub(crate) fn body(&self) -> Option<&Element> {
        self.root
            .children()
            .iter()
            .filter_map(Node::as_element)
            .find(|element| element.role == Role::Body)
    }

    /// The `w:body` element, mutably.
    pub(crate) fn body_mut(&mut self) -> Option<&mut Element> {
        self.root
            .children_mut()
            .iter_mut()
            .filter_map(Node::as_element_mut)
            .find(|element| element.role == Role::Body)
    }

    /// Normalize every container in the tree.
    ///
    /// Inserts an empty paragraph into an empty cell or body, and one empty row
    /// into an empty table. Runs after any edit that can empty a container.
    pub(crate) fn normalize(&mut self) {
        let prefix = self.word_prefix.clone();
        normalize_element(&mut self.root, &prefix);
    }
}

pub(crate) fn normalize_element(element: &mut Element, prefix: &str) {
    for child in element.children_mut() {
        if let Node::Element(child) = child {
            normalize_element(child, prefix);
        }
    }

    match element.role() {
        Role::Cell | Role::Body if element.blocks().next().is_none() => {
            element.push_child(Node::Element(empty_paragraph(prefix)));
        }
        Role::Table if element.rows().next().is_none() => {
            element.push_child(Node::Element(empty_row(prefix)));
        }
        _ => {}
    }
}

/// An empty `w:p` element.
pub(crate) fn empty_paragraph(prefix: &str) -> Element {
    let tag = format!("<{prefix}:p/>");
    Element::self_closing(format!("{prefix}:p"), Role::Paragraph, tag.into_bytes())
}

/// An empty `w:tr` with one cell that holds one empty paragraph.
pub(crate) fn empty_row(prefix: &str) -> Element {
    let paragraph = empty_paragraph(prefix);
    let cell = Element::new(
        format!("{prefix}:tc"),
        Role::Cell,
        format!("<{prefix}:tc>").into_bytes(),
        format!("</{prefix}:tc>").into_bytes(),
        false,
        vec![Node::Element(paragraph)],
    );
    Element::new(
        format!("{prefix}:tr"),
        Role::Row,
        format!("<{prefix}:tr>").into_bytes(),
        format!("</{prefix}:tr>").into_bytes(),
        false,
        vec![Node::Element(cell)],
    )
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]

    use super::*;

    fn el(name: &str, role: Role, children: Vec<Node>) -> Element {
        Element::new(
            name.to_string(),
            role,
            format!("<{name}>").into_bytes(),
            format!("</{name}>").into_bytes(),
            false,
            children,
        )
    }

    fn text(value: &str) -> Node {
        Node::Text(TextNode::original(
            value.as_bytes().to_vec(),
            value.to_string(),
        ))
    }

    fn paragraph(text_value: &str) -> Element {
        el(
            "w:p",
            Role::Paragraph,
            vec![Node::Element(el("w:t", Role::Text, vec![text(text_value)]))],
        )
    }

    fn cell(children: Vec<Node>) -> Element {
        el("w:tc", Role::Cell, children)
    }

    fn row(cells: Vec<Node>) -> Element {
        el("w:tr", Role::Row, cells)
    }

    fn table(rows: Vec<Node>) -> Element {
        el("w:tbl", Role::Table, rows)
    }

    fn body(children: Vec<Node>) -> Element {
        el("w:body", Role::Body, children)
    }

    fn document(body_element: Element) -> Document {
        let root = el(
            "w:document",
            Role::Document,
            vec![Node::Element(body_element)],
        );
        Document::new(Vec::new(), root, Vec::new(), "w".to_string())
    }

    #[test]
    fn role_helpers_classify_blocks_and_properties() {
        assert!(Role::Paragraph.is_block());
        assert!(Role::Table.is_block());
        assert!(!Role::CellProps.is_block());
        assert!(Role::CellProps.is_property());
        assert!(!Role::Paragraph.is_property());
    }

    #[test]
    fn blocks_skips_properties_and_text() {
        let cell = cell(vec![
            Node::Element(el("w:tcPr", Role::CellProps, vec![])),
            Node::Element(paragraph("hello")),
            text("   "),
        ]);
        assert_eq!(cell.blocks().count(), 1);
    }

    #[test]
    fn text_concatenates_all_descendants() {
        let p = el(
            "w:p",
            Role::Paragraph,
            vec![
                Node::Element(el("w:t", Role::Text, vec![text("Hel")])),
                Node::Element(el("w:t", Role::Text, vec![text("lo")])),
            ],
        );
        assert_eq!(p.text(), "Hello");
    }

    #[test]
    fn text_node_edit_marks_it_dirty() {
        let mut node = TextNode::original(b"a&amp;b".to_vec(), "a&b".to_string());
        assert!(!node.is_dirty());
        assert_eq!(node.raw(), b"a&amp;b");
        node.set_value("a & b".to_string());
        assert!(node.is_dirty());
        assert_eq!(node.value(), "a & b");
    }

    #[test]
    fn normalize_inserts_paragraph_into_empty_cell() {
        let mut doc = document(body(vec![Node::Element(cell(vec![]))]));
        doc.normalize();
        let cell = doc.body().unwrap().cells().next().unwrap();
        assert_eq!(cell.blocks().count(), 1);
        assert_eq!(cell.blocks().next().unwrap().role(), Role::Paragraph);
    }

    #[test]
    fn normalize_inserts_paragraph_into_empty_body() {
        let mut doc = document(body(vec![]));
        doc.normalize();
        assert_eq!(doc.body().unwrap().blocks().count(), 1);
    }

    #[test]
    fn normalize_keeps_one_row_in_empty_table() {
        let mut doc = document(body(vec![Node::Element(table(vec![]))]));
        doc.normalize();
        let table = doc.body().unwrap().blocks().next().unwrap();
        assert_eq!(table.rows().count(), 1);
        let cell = table.rows().next().unwrap().cells().next().unwrap();
        assert_eq!(cell.blocks().count(), 1);
    }

    #[test]
    fn cloning_a_row_clones_cell_properties() {
        let properties = el("w:tcPr", Role::CellProps, vec![]);
        let original = row(vec![Node::Element(cell(vec![
            Node::Element(properties),
            Node::Element(paragraph("x")),
        ]))]);
        let clone = original.clone();
        let cell = clone.cells().next().unwrap();
        assert!(
            cell.children()
                .iter()
                .filter_map(Node::as_element)
                .any(|element| element.role() == Role::CellProps)
        );
    }

    #[test]
    fn empty_row_has_one_cell_and_one_paragraph() {
        let row = empty_row("w");
        assert_eq!(row.rows().count(), 0);
        assert_eq!(row.cells().count(), 1);
        assert_eq!(row.cells().next().unwrap().blocks().count(), 1);
    }
}