rust-docx 0.2.13

Rust parser, document model, and serializer for DOCX and legacy Word documents
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
use std::collections::BTreeMap;

use quick_xml::{events::Event, Reader};
use serde::{Deserialize, Serialize};

use crate::{
    parse::{parse_run_text, run_text_xml},
    xml::{
        decode_xml_entities, direct_child_tag, extract_balanced_tag_slices,
        extract_direct_child_tag_ranges, get_attribute_ref, tag_token_end,
    },
    DocNode, DocumentBlock, ParagraphChildNode, ParagraphNode, SourceRef, StructuredDocument,
    TableNode, TableRowNode,
};

/// The current block projection and the tracked changes recorded in the same source.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ReviewedDocument {
    #[serde(flatten)]
    pub document: StructuredDocument,
    pub revisions: Vec<DocumentRevision>,
    #[serde(default)]
    pub comments: Vec<crate::review::DocumentComment>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RevisionKind {
    Insertion,
    Deletion,
    MoveFrom,
    MoveTo,
    Formatting,
    CellMerge,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RevisionScope {
    Text,
    ParagraphMark,
    Paragraph,
    Section,
    Table,
    TableGrid,
    TableRow,
    TableCell,
}

/// Direct Word properties, including nested properties and their qualified attributes.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct WordProperty {
    pub name: String,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub attributes: BTreeMap<String, String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub children: Vec<WordProperty>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RevisionProperties {
    pub before: Vec<WordProperty>,
    pub after: Vec<WordProperty>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DocumentRevision {
    /// Unique within this document, including when different parts reuse a Word ID.
    pub id: String,
    pub kind: RevisionKind,
    pub scope: RevisionScope,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub author: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub date: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub move_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<RevisionProperties>,
    /// Half-open UTF-16 ranges in current paragraph text. A deletion has equal endpoints.
    /// Structural targets and text which cannot be aligned safely have no endpoints.
    pub source_refs: Vec<SourceRef>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub content: Vec<DocNode>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub child_start: Option<usize>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub child_end: Option<usize>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_index: Option<usize>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReviewContent {
    pub source_xml: String,
    pub children: Vec<ParagraphChildNode>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReviewRow {
    pub source_index: usize,
    pub source_xml: String,
    pub row: TableRowNode,
}

pub(crate) fn removed_fragments(xml: &str) -> Vec<&str> {
    let mut ranges = crate::xml::extract_balanced_tag_ranges(xml, "w:del");
    ranges.extend(crate::xml::extract_balanced_tag_ranges(xml, "w:moveFrom"));
    ranges.sort_by_key(|r| r.start);
    let mut end = 0;
    ranges
        .into_iter()
        .filter_map(|range| {
            if range.start < end {
                return None;
            }
            end = range.end;
            let fragment = &xml[range.start..range.end];
            fragment.contains("<w:r").then_some(fragment)
        })
        .collect()
}

pub(crate) fn visible_removed_xml(xml: &str) -> String {
    static TAGS: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
        regex::Regex::new(r"(<\/?)w:(delText|delInstrText|del|moveFrom)([ \t\r\n/>])").unwrap()
    });
    TAGS.replace_all(xml, |captures: &regex::Captures<'_>| {
        let name = match &captures[2] {
            "delText" => "t",
            "delInstrText" => "instrText",
            _ => "ins",
        };
        format!("{}w:{name}{}", &captures[1], &captures[3])
    })
    .into_owned()
}

pub(crate) fn fallback_content(xml: &str) -> Vec<ParagraphChildNode> {
    let parts = Default::default();
    let assets = Default::default();
    let context = crate::parse::ParseContext {
        relationships: Default::default(),
        content_types: Default::default(),
        parts: &parts,
        binary_assets: &assets,
        style_sheet: crate::parse::empty_style_sheet(),
        warnings: Default::default(),
    };
    crate::parse::parse_paragraph(
        &format!("<w:p>{}</w:p>", visible_removed_xml(xml)),
        &context,
    )
    .children
}

fn children(xml: &str) -> impl Iterator<Item = (String, &str)> {
    extract_direct_child_tag_ranges(xml)
        .into_iter()
        .map(|r| (r.tag_name, &xml[r.start..r.end]))
}

fn attribute(xml: &str, name: &str) -> Option<String> {
    let tag = &xml[..tag_token_end(xml, 0)?];
    get_attribute_ref(tag, name).map(decode_xml_entities)
}

fn revision_kind(name: &str) -> Option<RevisionKind> {
    Some(match name {
        "w:ins" | "w:cellIns" => RevisionKind::Insertion,
        "w:del" | "w:cellDel" => RevisionKind::Deletion,
        "w:moveFrom" => RevisionKind::MoveFrom,
        "w:moveTo" => RevisionKind::MoveTo,
        "w:cellMerge" => RevisionKind::CellMerge,
        "w:rPrChange" | "w:pPrChange" | "w:sectPrChange" | "w:tblPrChange" | "w:tblGridChange"
        | "w:tblPrExChange" | "w:trPrChange" | "w:tcPrChange" => RevisionKind::Formatting,
        _ => return None,
    })
}

fn property(name: String, xml: &str) -> WordProperty {
    let mut reader = Reader::from_str(xml);
    let mut attributes = BTreeMap::new();
    if let Ok(Event::Start(tag) | Event::Empty(tag)) = reader.read_event() {
        for attr in tag.attributes().flatten() {
            let key = attr.key.as_ref();
            if !key.starts_with("xmlns") {
                attributes.insert(key.to_owned(), decode_xml_entities(&attr.value));
            }
        }
    }
    WordProperty {
        name,
        attributes,
        children: properties(xml),
    }
}

fn properties(xml: &str) -> Vec<WordProperty> {
    children(xml)
        .filter(|(name, _)| revision_kind(name).is_none())
        .map(|(name, xml)| property(name, xml))
        .collect()
}

#[derive(Default)]
pub(crate) struct RevisionCollector {
    pub records: Vec<DocumentRevision>,
    next_ids: BTreeMap<String, usize>,
    // The two move ranges have distinct Word IDs and share a move name.
    pub(crate) moves: Vec<(RevisionKind, String, String)>,
}

impl RevisionCollector {
    fn record(
        &mut self,
        xml: &str,
        kind: RevisionKind,
        scope: RevisionScope,
        refs: &[SourceRef],
    ) -> usize {
        let index = self.records.len();
        let source_id = attribute(xml, "w:id");
        let key = format!("{}/revision/{kind:?}/{scope:?}/{}", refs[0].node_id,
            source_id.as_deref().unwrap_or("anonymous"));
        let next = self.next_ids.entry(key.clone()).or_default();
        let id = format!("{key}/{next}");
        *next += 1;
        let move_name = self
            .moves
            .iter()
            .rev()
            .find(|(side, _, _)| *side == kind)
            .map(|(_, _, name)| name.clone());
        self.records.push(DocumentRevision {
            id,
            source_id,
            author: attribute(xml, "w:author"),
            date: attribute(xml, "w:date"),
            kind,
            scope,
            move_name,
            text: None,
            properties: None,
            source_refs: refs.to_vec(),
            content: Vec::new(),
            child_start: None,
            child_end: None,
            source_index: None,
        });
        index
    }

    fn property_changes(&mut self, xml: &str, scope: RevisionScope, refs: &[SourceRef]) {
        for (name, change) in children(xml) {
            let Some(kind) = revision_kind(&name) else {
                continue;
            };
            let index = self.record(change, kind, scope, refs);
            if kind == RevisionKind::Formatting {
                let before = children(change)
                    .next()
                    .map(|(_, previous)| properties(previous))
                    .unwrap_or_default();
                self.records[index].properties = Some(RevisionProperties {
                    before,
                    after: properties(xml),
                });
            } else if kind == RevisionKind::CellMerge {
                let merge = |key| {
                    attribute(change, key)
                        .map(|value| WordProperty {
                            name: "w:vMerge".into(),
                            attributes: BTreeMap::from([("w:val".into(), value)]),
                            children: Vec::new(),
                        })
                        .into_iter()
                        .collect()
                };
                self.records[index].properties = Some(RevisionProperties {
                    before: merge("w:vMergeOrig"),
                    after: merge("w:vMerge"),
                });
            }
        }
    }

    pub fn paragraph(&mut self, xml: &str, block: &DocumentBlock, paragraph: &ParagraphNode) {
        if !has_markup(xml) {
            return;
        }
        let first = self.records.len();
        let mut p = ParagraphReview {
            collector: self,
            source: &block.source_refs[0],
            visible: String::new(),
            quoted: String::new(),
            offset: 0,
            child_index: 0,
            paragraph,
        };
        p.visit(xml, false);
        let aligned = p.visible == block.content;
        let end = block.content.encode_utf16().count();
        for revision in &mut p.collector.records[first..] {
            let target = &mut revision.source_refs[0];
            if revision.scope == RevisionScope::ParagraphMark {
                target.start = Some(end);
                target.end = Some(end);
            } else if !aligned {
                target.start = None;
                target.end = None;
                revision.child_start = None;
                revision.child_end = None;
            }
        }
    }

    pub fn final_section(&mut self, xml: &str, source: &SourceRef) {
        if xml.contains("w:sectPrChange") {
            self.property_changes(xml, RevisionScope::Section, std::slice::from_ref(source));
        }
    }

    pub fn table(&mut self, xml: &str, source: &SourceRef, table: &TableNode) {
        if !has_markup(xml) {
            return;
        }
        let targets = std::slice::from_ref(source);
        for (name, scope) in [
            ("w:tblPr", RevisionScope::Table),
            ("w:tblGrid", RevisionScope::TableGrid),
        ] {
            if let Some(props) = direct_child_tag(xml, name) {
                self.property_changes(props, scope, targets);
            }
        }
        let mut retained = 0;
        for (source_index, row_xml) in extract_balanced_tag_slices(xml, "w:tr")
            .into_iter()
            .enumerate()
        {
            let deleted = direct_child_tag(row_xml, "w:trPr")
                .and_then(|props| direct_child_tag(props, "w:del"))
                .is_some();
            if deleted {
                let first = self.records.len();
                if let Some(props) = direct_child_tag(row_xml, "w:trPr") {
                    self.property_changes(props, RevisionScope::TableRow, targets);
                }
                for record in &mut self.records[first..] {
                    record.source_index = Some(source_index);
                    if record.kind == RevisionKind::Deletion {
                        if let Some(removed) = table
                            .review_rows
                            .iter()
                            .flatten()
                            .find(|r| r.source_xml == row_xml)
                        {
                            let mut content = table.clone();
                            content.rows = vec![removed.row.clone()];
                            content.review_rows = None;
                            content.source_xml = None;
                            content.block_id =
                                Some(format!("{}/removed-row/{source_index}", source.node_id));
                            record.content.push(DocNode::Table(content));
                        }
                    }
                }
                continue;
            }
            let ri = retained;
            retained += 1;
            let Some(row) = table.rows.get(ri) else {
                continue;
            };
            let cells: Vec<_> = (0..row.cells.len())
                .map(|ci| SourceRef {
                    node_id: format!("{}/row/{ri}/cell/{ci}", source.node_id),
                    ..source.clone()
                })
                .collect();
            let row_targets = if cells.is_empty() {
                targets
            } else {
                cells.as_slice()
            };
            for tag in ["w:trPr", "w:tblPrEx"] {
                if let Some(props) = direct_child_tag(row_xml, tag) {
                    self.property_changes(props, RevisionScope::TableRow, row_targets);
                }
            }
            for (cell_xml, cell) in extract_balanced_tag_slices(row_xml, "w:tc")
                .into_iter()
                .zip(&cells)
            {
                if let Some(props) = direct_child_tag(cell_xml, "w:tcPr") {
                    self.property_changes(
                        props,
                        RevisionScope::TableCell,
                        std::slice::from_ref(cell),
                    );
                }
            }
        }
    }
}

fn has_markup(xml: &str) -> bool {
    [
        "<w:ins",
        "<w:del",
        "<w:move",
        "Change",
        "<w:cellIns",
        "<w:cellDel",
        "<w:cellMerge",
    ]
    .iter()
    .any(|marker| xml.contains(marker))
}

struct ParagraphReview<'a> {
    collector: &'a mut RevisionCollector,
    source: &'a SourceRef,
    visible: String,
    quoted: String,
    offset: usize,
    child_index: usize,
    paragraph: &'a ParagraphNode,
}

impl ParagraphReview<'_> {
    fn visit(&mut self, xml: &str, removed: bool) {
        for (name, child) in children(xml) {
            match name.as_str() {
                "w:r" => self.run(child, removed),
                "w:ins" | "w:del" | "w:moveFrom" | "w:moveTo" => {
                    let kind = revision_kind(&name).unwrap();
                    let index = self.collector.record(
                        child,
                        kind,
                        RevisionScope::Text,
                        std::slice::from_ref(self.source),
                    );
                    let start = self.offset;
                    let child_start = self.child_index;
                    let hidden =
                        removed || matches!(kind, RevisionKind::Deletion | RevisionKind::MoveFrom);
                    let begin = if hidden {
                        self.quoted.len()
                    } else {
                        self.visible.len()
                    };
                    self.visit(child, hidden);
                    let revision = &mut self.collector.records[index];
                    revision.text = Some(
                        (if hidden { &self.quoted } else { &self.visible })[begin..].to_owned(),
                    );
                    revision.source_refs[0].start = Some(start);
                    revision.source_refs[0].end = Some(self.offset);
                    revision.child_start = Some(child_start);
                    revision.child_end = Some(self.child_index);
                    if hidden {
                        let children = self
                            .paragraph
                            .review_content
                            .iter()
                            .flatten()
                            .find(|fragment| fragment.source_xml == child)
                            .map(|fragment| fragment.children.clone())
                            .unwrap_or_else(|| fallback_content(child));
                        let mut content = self.paragraph.clone();
                        content.block_id = Some(format!("{}/content", revision.id));
                        content.children = children;
                        content.review_content = None;
                        content.source_xml = None;
                        content.source_text_patch = None;
                        content.source_run_provenance = None;
                        revision.content.push(DocNode::Paragraph(content));
                    }
                }
                "w:moveFromRangeStart"
                | "w:moveToRangeStart"
                | "w:moveFromRangeEnd"
                | "w:moveToRangeEnd" => {
                    let side = if name.starts_with("w:moveFrom") {
                        RevisionKind::MoveFrom
                    } else {
                        RevisionKind::MoveTo
                    };
                    if let Some(id) = attribute(child, "w:id") {
                        if name.ends_with("Start") {
                            if let Some(label) = attribute(child, "w:name") {
                                self.collector.moves.push((side, id, label));
                            }
                        } else {
                            self.collector
                                .moves
                                .retain(|(s, key, _)| *s != side || *key != id);
                        }
                    }
                }
                "w:pPr" => {
                    let refs = std::slice::from_ref(self.source);
                    self.collector
                        .property_changes(child, RevisionScope::Paragraph, refs);
                    if let Some(mark) = direct_child_tag(child, "w:rPr") {
                        self.collector
                            .property_changes(mark, RevisionScope::ParagraphMark, refs);
                    }
                    if let Some(section) = direct_child_tag(child, "w:sectPr") {
                        self.collector
                            .property_changes(section, RevisionScope::Section, refs);
                    }
                }
                "w:hyperlink" | "w:sdt" | "w:sdtContent" | "w:smartTag" | "w:customXml"
                | "w:fldSimple" | "w:dir" | "w:bdo" => self.visit(child, removed),
                "mc:AlternateContent" => {
                    if let Some(active) = direct_child_tag(child, "mc:Choice")
                        .or_else(|| direct_child_tag(child, "mc:Fallback"))
                    {
                        self.visit(active, removed);
                    }
                }
                _ => {}
            }
        }
    }

    fn run(&mut self, xml: &str, removed: bool) {
        let active = run_text_xml(xml);
        let text = if removed && active.contains("w:delText") {
            parse_run_text(
                &active
                    .replace("<w:delText", "<w:t")
                    .replace("</w:delText>", "</w:t>"),
            )
        } else {
            parse_run_text(&active)
        };
        let start = self.offset;
        let child_start = self.child_index;
        self.quoted.push_str(&text);
        if !removed {
            self.visible.push_str(&text);
            self.offset += text.encode_utf16().count();
            self.child_index += crate::parse::parse_run_text_tokens(&active)
                .iter()
                .filter(|t| !t.text.is_empty() || t.note_reference.is_some())
                .count();
            self.child_index += extract_balanced_tag_slices(&active, "w:drawing").len()
                + extract_balanced_tag_slices(&active, "w:pict").len();
        }
        if let Some(props) = direct_child_tag(xml, "w:rPr") {
            let target = SourceRef {
                start: Some(start),
                end: Some(self.offset),
                ..self.source.clone()
            };
            let first = self.collector.records.len();
            self.collector
                .property_changes(props, RevisionScope::Text, &[target]);
            for revision in &mut self.collector.records[first..] {
                revision.child_start = Some(child_start);
                revision.child_end = Some(self.child_index);
            }
        }
    }
}