f-office-docx 0.2.1

DOCX model and Word's layout rules.
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
//! The text of a part with every tracked change accepted, which a target that prints without
//! markup shows (`Markup::PrintsNoMarkup` in `src/quirks.rs`).

use std::collections::HashMap;

use f_office_xml::{Document, NodeId};

use crate::ns::{MC, W};
use crate::params::TEXT_BUFFER_MARK_LENGTH;
use crate::reader::settings::ReaderSettings;

/// Accepts every tracked change of a part (ECMA-376 Part 1, 17.13.5) as a target that prints
/// without markup shows it. Deleted and moved-away content goes, inserted and moved-in content
/// stays as plain content, a paragraph whose mark is deleted or moved away joins the next
/// paragraph, deleted table rows go, a table whose rows all go keeps no height, deleted cells
/// stay with their content, and the records of
/// earlier properties go, so that nothing in the part reads as a change. The insertions that
/// the reader's `settings` make one revision keep one number on their runs, and the deleted
/// runs leave their characters with a comment's reference counted as the settings say.
pub(crate) fn accept(doc: &mut Document, settings: ReaderSettings) {
    if let Ok(root) = doc.root() {
        note_inserted_runs(doc, root, settings);
        note_deleted_characters(doc, root, settings);
        accept_below(doc, root);
    }
}

/// Leaves on the first run after each deleted run, and after each deleted paragraph mark, the
/// characters that they held, which stay in Word's text buffers once the changes are accepted:
/// a deleted run's characters as the same run counts live, and a mark for a deleted paragraph
/// mark. The walk goes in
/// document order and leaves out deleted rows. A run after deleted runs is also marked as one,
/// at which a target's writer can start a text object.
fn note_deleted_characters(doc: &mut Document, root: NodeId, settings: ReaderSettings) {
    let mut found = Vec::new();
    let mut pending = 0;
    let mut after_runs = false;
    // `None` stands where a deleted paragraph mark ends its paragraph.
    let mut stack = vec![Some(root)];
    while let Some(item) = stack.pop() {
        let Some(node) = item else {
            pending += TEXT_BUFFER_MARK_LENGTH;
            continue;
        };
        if REMOVED.iter().any(|name| doc.is(node, W, name)) && doc.child(node, W, "r").is_some() {
            pending += deleted_characters(doc, node, settings);
            after_runs = true;
            continue;
        }
        if doc.is(node, W, "tr") && marked(doc, node, "trPr", &REMOVED) {
            continue;
        }
        if doc.is(node, W, "r") && pending > 0 {
            found.push((
                node,
                std::mem::take(&mut pending),
                std::mem::take(&mut after_runs),
            ));
        }
        if mark_removed(doc, node) {
            stack.push(None);
        }
        let children: Vec<NodeId> = doc.child_elements(node).collect();
        stack.extend(children.into_iter().rev().map(Some));
    }
    for (run, characters, after_runs) in found {
        doc.set_attribute(
            run,
            Some(crate::ns::NOTE),
            "buffered",
            &characters.to_string(),
        );
        if after_runs {
            doc.set_attribute(run, Some(crate::ns::NOTE), "removed", "1");
        }
    }
}

/// The characters that the runs below `node` hold in Word's text, which a deleted run counts
/// as the same run counts live.
fn deleted_characters(doc: &Document, node: NodeId, settings: ReaderSettings) -> usize {
    doc.child_elements(node)
        .map(|child| {
            if doc.is(child, W, "r") {
                run_characters(doc, child, settings)
            } else {
                deleted_characters(doc, child, settings)
            }
        })
        .sum()
}

/// The children of a run that the body reader reads as one mark of content each, such as a
/// tab, a break, a field's mark, a note's reference or own mark, a separator or a drawing.
const RUN_MARKS: [&str; 18] = [
    "tab",
    "ptab",
    "cr",
    "br",
    "noBreakHyphen",
    "softHyphen",
    "sym",
    "fldChar",
    "footnoteReference",
    "footnoteRef",
    "endnoteReference",
    "endnoteRef",
    "annotationRef",
    "separator",
    "continuationSeparator",
    "drawing",
    "pict",
    "object",
];

/// The characters of the children of the run, or of the branch of alternate content, `node`
/// in Word's text, as the body reader reads them: the letters of text and field codes, a mark
/// of [`TEXT_BUFFER_MARK_LENGTH`] for each of [`RUN_MARKS`], a comment's reference as
/// the reader's `settings` say, only the branch of alternate content that the reader shows
/// (`body::alternate_branch`), and nothing for a child that the reader leaves out.
fn run_characters(doc: &Document, node: NodeId, settings: ReaderSettings) -> usize {
    doc.child_elements(node)
        .map(|child| {
            let local = doc.element(child).map_or("", |e| e.name.local);
            match local {
                "AlternateContent" if doc.is(child, MC, "AlternateContent") => {
                    crate::body::alternate_branch(doc, child)
                        .map_or(0, |branch| run_characters(doc, branch, settings))
                }
                "t" | "delText" | "instrText" | "delInstrText" => {
                    crate::buffers::characters(&doc.text_content(child))
                }
                "commentReference" => settings.comment_anchor_length(),
                _ if RUN_MARKS.contains(&local) => TEXT_BUFFER_MARK_LENGTH,
                _ => 0,
            }
        })
        .sum()
}

/// Leaves on each run of an insertion, or of moved-in content, a number of its revision, which
/// the runs keep as a revision of their own once the change is accepted: Word starts a text
/// object where such a revision begins or ends, and keeps adjacent insertions of one revision in
/// one object. The reader's `settings` say which insertions are one revision: those of one
/// author, or of one author and minute.
fn note_inserted_runs(doc: &mut Document, root: NodeId, settings: ReaderSettings) {
    // Each revision gets a number, in the order the walk meets it.
    let mut revisions: HashMap<(&str, Option<&str>), u32> = HashMap::new();
    let mut found = Vec::new();
    let mut stack = vec![(root, None::<u32>)];
    while let Some((node, change)) = stack.pop() {
        let change = if doc.is(node, W, "ins") || doc.is(node, W, "moveTo") {
            let author = doc.attribute(node, Some(W), "author").unwrap_or("");
            let date = doc.attribute(node, Some(W), "date");
            let number = u32::try_from(revisions.len() + 1).unwrap_or(u32::MAX);
            Some(
                *revisions
                    .entry(settings.revision_key(author, date))
                    .or_insert(number),
            )
        } else {
            change
        };
        if let (true, Some(number)) = (doc.is(node, W, "r"), change) {
            found.push((node, number));
        }
        stack.extend(doc.child_elements(node).map(|child| (child, change)));
    }
    for (run, number) in found {
        doc.set_attribute(run, Some(crate::ns::NOTE), "change", &number.to_string());
    }
}

/// What accepting the changes does to one node.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Role {
    /// The node stays.
    Kept,
    /// The node goes with all it holds.
    Removed,
    /// The node goes and its children take its place.
    Unwrapped,
}

/// The elements of a tracked change that take away what they hold: a deletion (`w:del`) and
/// the place that moved content leaves (`w:moveFrom`), as runs and as the marks of paragraphs
/// and rows (ECMA-376 Part 1, 17.13.5).
pub(crate) const REMOVED: [&str; 2] = ["del", "moveFrom"];

/// The records of earlier properties, and the marks of inserted, deleted or merged cells, which
/// go. A deleted cell stays with what it holds.
const RECORDS: [&str; 12] = [
    "rPrChange",
    "pPrChange",
    "sectPrChange",
    "tblPrChange",
    "tblPrExChange",
    "tblGridChange",
    "trPrChange",
    "tcPrChange",
    "numberingChange",
    "cellIns",
    "cellDel",
    "cellMerge",
];

/// The elements that hold the blocks of a story, between which a paragraph whose mark is
/// deleted can join the next one. Other elements between two paragraphs, such as the marks of
/// bookmarks and comment ranges, do not stop the join.
const BLOCKS: [&str; 6] = ["p", "tbl", "sdt", "customXml", "sectPr", "altChunk"];

/// Whether a node is one of the [`BLOCKS`].
fn is_block(doc: &Document, node: NodeId) -> bool {
    BLOCKS.iter().any(|name| doc.is(node, W, name))
}

fn role(doc: &Document, node: NodeId) -> Role {
    let Some(element) = doc.element(node) else {
        return Role::Kept;
    };
    let in_w = element
        .name
        .namespace
        .is_some_and(|ns| doc.namespace_uri(ns) == W);
    if !in_w {
        return Role::Kept;
    }
    let local = element.name.local;
    match local {
        // A deleted run or paragraph mark, and the mark of a deleted row.
        _ if REMOVED.contains(&local) => Role::Removed,
        // An inserted run stays as a plain run; an empty mark of an insertion goes.
        "ins" | "moveTo" => Role::Unwrapped,
        "tr" if marked(doc, node, "trPr", &REMOVED) => Role::Removed,
        _ if RECORDS.contains(&local) => Role::Removed,
        _ => Role::Kept,
    }
}

/// Whether the properties `props` of a node hold one of the marks `marks`.
fn marked(doc: &Document, node: NodeId, props: &str, marks: &[&str]) -> bool {
    doc.child(node, W, props).is_some_and(|props| {
        doc.child_elements(props)
            .any(|mark| marks.iter().any(|name| doc.is(mark, W, name)))
    })
}

/// Whether the mark of a paragraph is deleted or moved away (`w:pPr/w:rPr/w:del`).
fn mark_removed(doc: &Document, paragraph: NodeId) -> bool {
    doc.is(paragraph, W, "p")
        && doc
            .child(paragraph, W, "pPr")
            .is_some_and(|ppr| marked(doc, ppr, "rPr", &REMOVED))
}

/// The children of `node` that stay, in order, each with whether it is a paragraph whose mark
/// goes. The children of an unwrapped node take its place.
fn kept_children(doc: &Document, node: NodeId, out: &mut Vec<(NodeId, bool)>) {
    for &child in doc.children(node) {
        match role(doc, child) {
            Role::Removed => {}
            Role::Unwrapped => kept_children(doc, child, out),
            Role::Kept => out.push((child, mark_removed(doc, child))),
        }
    }
}

fn accept_below(doc: &mut Document, node: NodeId) {
    let mut kept = Vec::new();
    kept_children(doc, node, &mut kept);
    let marks: Vec<(NodeId, NodeId)> = kept
        .iter()
        .filter_map(|&(child, _)| Some((child, mark_in_deleted_rows(doc, child)?)))
        .collect();
    for &child in kept
        .iter()
        .map(|(child, _)| child)
        .chain(marks.iter().map(|(_, p)| p))
    {
        accept_below(doc, child);
    }
    let children = join_paragraphs(doc, &kept, &marks);
    // A table whose rows all go leaves an empty table with no height, which keeps the space
    // after of the paragraph before it and the space before of the paragraph after it apart,
    // as a table does.
    for &child in &children {
        if doc.is(child, W, "tbl") && !holds_row(doc, child) {
            doc.set_children(child, Vec::new());
        }
    }
    doc.set_children(node, children);
}

/// Whether a table, or an element that wraps rows in it, holds a row: as its child, or inside
/// content controls, custom XML or alternate content.
fn holds_row(doc: &Document, node: NodeId) -> bool {
    doc.child_elements(node).any(|child| {
        doc.is(child, W, "tr")
            || ["sdt", "sdtContent", "customXml"]
                .iter()
                .any(|name| doc.is(child, W, name))
                && holds_row(doc, child)
            || ["AlternateContent", "Choice", "Fallback"]
                .iter()
                .any(|name| doc.is(child, MC, name))
                && holds_row(doc, child)
    })
}

/// Whether a node holds a run with more than its properties and the mark of a page break that
/// Word last drew.
fn holds_content(doc: &Document, node: NodeId) -> bool {
    if doc.is(node, W, "r") {
        return doc
            .child_elements(node)
            .any(|child| !doc.is(child, W, "rPr") && !doc.is(child, W, "lastRenderedPageBreak"));
    }
    doc.child_elements(node)
        .any(|child| holds_content(doc, child))
}

/// The first paragraph in the cells of a table's deleted rows whose own mark is not deleted.
fn mark_in_deleted_rows(doc: &Document, table: NodeId) -> Option<NodeId> {
    let cells = |row: NodeId| doc.child_elements(row).filter(|&c| doc.is(c, W, "tc"));
    doc.is(table, W, "tbl")
        .then(|| doc.child_elements(table))?
        .filter(|&row| doc.is(row, W, "tr") && role(doc, row) == Role::Removed)
        .flat_map(cells)
        .flat_map(|cell| doc.child_elements(cell))
        .find(|&paragraph| doc.is(paragraph, W, "p") && !mark_removed(doc, paragraph))
}

/// The properties of the next paragraph mark that stays among `blocks`, which start with a
/// table: in the first cell of the first table whose rows do not all go, or, in a table whose
/// rows all go, the first paragraph of its deleted rows whose mark is not deleted (`marks`, from
/// [`mark_in_deleted_rows`]); after tables whose rows and marks all go, the next paragraph.
/// Another block, such as a content control, has none.
fn next_properties(
    doc: &Document,
    blocks: impl Iterator<Item = NodeId>,
    marks: &[(NodeId, NodeId)],
) -> Option<NodeId> {
    let mark = |table: NodeId| marks.iter().find(|&&(t, _)| t == table).map(|&(_, p)| p);
    let paragraph = blocks
        .filter(|&block| is_block(doc, block))
        .find_map(|block| {
            if !doc.is(block, W, "tbl") {
                return Some(Some(block));
            }
            match doc.child(block, W, "tr") {
                Some(row) => Some(doc.child(row, W, "tc").and_then(|c| doc.child(c, W, "p"))),
                None => mark(block).map(Some),
            }
        })??;
    doc.is(paragraph, W, "p")
        .then(|| doc.child(paragraph, W, "pPr"))
        .flatten()
}

/// Keeps the content of a paragraph whose mark goes before a table, with the properties `props`
/// of the next paragraph that stays ([`next_properties`]) in place of its own, as a joined
/// paragraph takes those of the next paragraph, and returns whether anything is left in it; a
/// paragraph with nothing left goes. It takes no section break from them, as the paragraph whose
/// properties it takes keeps its own.
fn keep_before_table(doc: &mut Document, paragraph: NodeId, props: Option<NodeId>) -> bool {
    let own: Vec<NodeId> = doc
        .children(paragraph)
        .iter()
        .copied()
        .filter(|&child| !doc.is(child, W, "pPr"))
        .collect();
    let stays = own.iter().any(|&child| holds_content(doc, child));
    if stays {
        let mut content = Vec::new();
        if let (Some(own_props), Some(props)) = (doc.child(paragraph, W, "pPr"), props) {
            let taken = doc
                .children(props)
                .iter()
                .copied()
                .filter(|&child| !doc.is(child, W, "sectPr"))
                .collect();
            doc.set_children(own_props, taken);
            content.push(own_props);
        }
        content.extend(own);
        doc.set_children(paragraph, content);
    }
    stays
}

/// Joins each paragraph whose mark goes to the next paragraph, when the next block is one: the
/// content of both is the joined paragraph's, with the properties of the next one, whose mark
/// stays. Before a table, whether or not its rows go, such a paragraph does not join: it keeps
/// its content with the properties of the next paragraph that stays, or goes when nothing is
/// left in it ([`keep_before_table`]). A paragraph at the end of its story keeps its mark.
///
/// The walk goes back from the last child and keeps the place of the next block that stays, so
/// that no child is read again for each paragraph before it, and it gathers the paragraphs that
/// join one paragraph, so that the joined children are built once for a chain of any length.
fn join_paragraphs(
    doc: &mut Document,
    kept: &[(NodeId, bool)],
    marks: &[(NodeId, NodeId)],
) -> Vec<NodeId> {
    let mut children: Vec<Option<NodeId>> = kept.iter().map(|&(child, _)| Some(child)).collect();
    // The place of the next block that stays, and the paragraphs that join it, the last first.
    let mut next: Option<usize> = None;
    let mut joining: Vec<NodeId> = Vec::new();
    for (index, &(child, joins)) in kept.iter().enumerate().rev() {
        // The children from the next block that stays on: those between are no blocks.
        let later = next.and_then(|at| children.get(at..)).unwrap_or_default();
        let fate = if joins {
            fate(doc, child, later, marks)
        } else {
            Fate::Stays
        };
        match fate {
            Fate::Joins => joining.push(child),
            Fate::Goes => {}
            Fate::Stays if is_block(doc, child) => {
                join(doc, next.and_then(|at| kept.get(at)), &mut joining);
                next = Some(index);
                continue;
            }
            Fate::Stays => continue,
        }
        if let Some(slot) = children.get_mut(index) {
            *slot = None;
        }
    }
    join(doc, next.and_then(|at| kept.get(at)), &mut joining);
    children.into_iter().flatten().collect()
}

/// What becomes of a paragraph whose mark goes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Fate {
    /// It stays, before a table with the properties of the next paragraph that stays, or with
    /// its own mark before another block or at the end of its story.
    Stays,
    /// It goes before a table, with nothing left in it.
    Goes,
    /// It joins the next paragraph.
    Joins,
}

/// The fate of the paragraph `paragraph` whose mark goes, before the children `later`, which
/// start with the next block that stays; before a table, it keeps what it holds with the
/// properties of the next paragraph that stays ([`keep_before_table`]).
fn fate(
    doc: &mut Document,
    paragraph: NodeId,
    later: &[Option<NodeId>],
    marks: &[(NodeId, NodeId)],
) -> Fate {
    let Some(&Some(block)) = later.first() else {
        return Fate::Stays;
    };
    count_join_steps(1);
    if doc.is(block, W, "p") {
        return Fate::Joins;
    }
    if !doc.is(block, W, "tbl") {
        return Fate::Stays;
    }
    let blocks = later
        .iter()
        .flatten()
        .copied()
        .inspect(|_| count_join_steps(1));
    let props = next_properties(doc, blocks, marks);
    if keep_before_table(doc, paragraph, props) {
        Fate::Stays
    } else {
        Fate::Goes
    }
}

/// Gives the paragraph `next` the content of the paragraphs `parts` that join it, given the last
/// first, and empties `parts`: its own properties, then the content of each part in order, then
/// its own content. A paragraph that nothing joins stays as it is.
fn join(doc: &mut Document, next: Option<&(NodeId, bool)>, parts: &mut Vec<NodeId>) {
    let (Some(&(next, _)), false) = (next, parts.is_empty()) else {
        return;
    };
    let is_props = |child: &&NodeId| doc.is(**child, W, "pPr");
    count_join_steps(doc.children(next).len());
    let mut joined: Vec<NodeId> = doc
        .children(next)
        .iter()
        .filter(is_props)
        .copied()
        .collect();
    for &part in parts.iter().rev().chain([&next]) {
        count_join_steps(doc.children(part).len());
        joined.extend(
            doc.children(part)
                .iter()
                .filter(|child| !is_props(child))
                .copied(),
        );
    }
    doc.set_children(next, joined);
    parts.clear();
}

#[cfg(test)]
thread_local! {
    /// The steps of the joins of paragraph marks on this thread: the children that they read
    /// to find the next block or the properties before a table, and the children that they
    /// move into a joined paragraph. A test bounds the work of a join by this count, and not
    /// by a time.
    static JOIN_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// Counts `children` steps of a join of paragraph marks (`JOIN_STEPS`). Only a test build
/// keeps the count.
fn count_join_steps(children: usize) {
    #[cfg(test)]
    JOIN_STEPS.with(|steps| steps.set(steps.get() + children));
    #[cfg(not(test))]
    let _ = children;
}

#[cfg(test)]
mod tests;