f-office-docx 0.3.0

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
//! The check after the named edits: the text blocks that the new file must have, made from the
//! text blocks of the file before and what each edit does, and their comparison with the text
//! blocks of the new file.

use std::fmt;

use super::Place;
use crate::text_blocks::{Address, AddressStep, TextBlock, TextBlockKind};

/// What one named edit does to the text blocks.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Outcome {
    /// The paragraph's text with `find` replaced by `with`.
    Replace {
        at: Address,
        find: String,
        with: String,
    },
    /// A new paragraph with `text` and `style`.
    Insert {
        at: Address,
        place: Place,
        text: String,
        style: Option<String>,
    },
    /// The block or the row goes.
    Delete { at: Address },
    /// The block takes the style; none for a table, whose text block has no style.
    Style { at: Address, style: Option<String> },
    /// All the text of a paragraph becomes `text`; all the blocks of a cell become one
    /// paragraph with `style` and `text`.
    SetText {
        at: Address,
        text: String,
        style: Option<String>,
    },
    /// A new row with one paragraph in each cell, with its style and its text.
    InsertRow {
        at: Address,
        place: Place,
        cells: Vec<(Option<String>, String)>,
    },
}

/// A block of the expected tree: what the new file must have where the block was, or a new
/// block.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Node {
    Paragraph {
        from: Option<Address>,
        style: Option<String>,
        /// The text, or none when the check cannot know it.
        text: Option<String>,
        gone: bool,
        before: Vec<Node>,
        after: Vec<Node>,
    },
    Table {
        from: Option<Address>,
        rows: Vec<Row>,
        gone: bool,
        before: Vec<Node>,
        after: Vec<Node>,
    },
}

/// A row of the expected tree: its cells, each with its blocks, and the new rows before and
/// after it.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct Row {
    cells: Vec<Vec<Node>>,
    gone: bool,
    before: Vec<Row>,
    after: Vec<Row>,
}

/// The text blocks that the new file must have after a list's named edits, in order: each with
/// its address, its kind, and for a paragraph its style and its text, which is none where the
/// check cannot know it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExpectedBlocks {
    blocks: Vec<(Address, Expected)>,
}

/// One expected block.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Expected {
    Paragraph {
        style: Option<String>,
        text: Option<String>,
    },
    Table {
        rows: usize,
    },
}

/// How the new file's text blocks differ from the expected ones: the first difference.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Mismatch {
    /// The address where they differ.
    pub at: String,
    /// What the edits expect there.
    pub expected: String,
    /// What the new file has there.
    pub found: String,
}

impl fmt::Display for Mismatch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "at {} the new file has {}, and the edits expect {}",
            self.at, self.found, self.expected
        )
    }
}

impl std::error::Error for Mismatch {}

impl ExpectedBlocks {
    /// The text blocks that `outcomes` make of `blocks`.
    pub(super) fn new(blocks: &[TextBlock], outcomes: &[Outcome]) -> Self {
        let mut body = tree(blocks);
        for outcome in outcomes {
            apply(&mut body, outcome);
        }
        let mut flat = Vec::new();
        flatten(&body, None, &mut flat);
        Self { blocks: flat }
    }

    /// Compares the text blocks of the new file with the expected ones.
    ///
    /// # Errors
    ///
    /// Returns the first difference.
    pub fn compare(&self, after: &[TextBlock]) -> Result<(), Mismatch> {
        for index in 0..self.blocks.len().max(after.len()) {
            let expected = self.blocks.get(index);
            let found = after.get(index);
            let same = match (expected, found) {
                (Some((address, expected)), Some(block)) => {
                    *address == block.address && expected.matches(&block.kind)
                }
                _ => false,
            };
            if !same {
                return Err(Mismatch {
                    at: expected
                        .map(|(address, _)| address.to_string())
                        .or_else(|| found.map(|block| block.address.to_string()))
                        .unwrap_or_default(),
                    expected: expected
                        .map_or_else(|| "no block".to_owned(), |(a, e)| e.describe(a)),
                    found: found.map_or_else(|| "no block".to_owned(), describe_block),
                });
            }
        }
        Ok(())
    }
}

impl Expected {
    fn matches(&self, kind: &TextBlockKind) -> bool {
        match (self, kind) {
            (
                Self::Paragraph { style, text },
                TextBlockKind::Paragraph {
                    style: found_style,
                    text: found_text,
                },
            ) => style == found_style && text.as_ref().is_none_or(|text| text == found_text),
            (Self::Table { rows }, TextBlockKind::Table { rows: found }) => rows == found,
            _ => false,
        }
    }

    fn describe(&self, address: &Address) -> String {
        match self {
            Self::Paragraph { style, text } => format!(
                "the paragraph {address} with the style {} and the text {}",
                style.as_deref().unwrap_or("of the default"),
                text.as_ref().map_or_else(
                    || "that the edits do not know".to_owned(),
                    |text| format!("{text:?}")
                )
            ),
            Self::Table { rows } => format!("the table {address} of {rows} rows"),
        }
    }
}

/// A text block of the new file, for a message.
fn describe_block(block: &TextBlock) -> String {
    match &block.kind {
        TextBlockKind::Paragraph { style, text } => format!(
            "the paragraph {} with the style {} and the text {text:?}",
            block.address,
            style.as_deref().unwrap_or("of the default")
        ),
        TextBlockKind::Table { rows } => format!("the table {} of {rows} rows", block.address),
    }
}

/// The tree of the text blocks `blocks`, which come in the order of the document, a table
/// before the blocks of its cells.
fn tree(blocks: &[TextBlock]) -> Vec<Node> {
    let mut body = Vec::new();
    for block in blocks {
        let node = match &block.kind {
            TextBlockKind::Paragraph { style, text } => Node::Paragraph {
                from: Some(block.address.clone()),
                style: style.clone(),
                text: Some(text.clone()),
                gone: false,
                before: Vec::new(),
                after: Vec::new(),
            },
            TextBlockKind::Table { rows } => Node::Table {
                from: Some(block.address.clone()),
                rows: vec![Row::default(); *rows],
                gone: false,
                before: Vec::new(),
                after: Vec::new(),
            },
        };
        if let Some(container) = container(&mut body, block.address.container()) {
            container.push(node);
        }
    }
    body
}

/// The blocks of the cell or the body that `steps` name, in the tree `body`, as the blocks of
/// the file before number them.
fn container<'t>(body: &'t mut Vec<Node>, steps: &[AddressStep]) -> Option<&'t mut Vec<Node>> {
    let [
        AddressStep::Table(table),
        AddressStep::Row(row),
        AddressStep::Cell(cell),
        rest @ ..,
    ] = steps
    else {
        return steps.is_empty().then_some(body);
    };
    let Node::Table { rows, .. } = body
        .iter_mut()
        .filter(|node| matches!(node, Node::Table { .. }))
        .nth(table.get() - 1)?
    else {
        return None;
    };
    let row = rows.get_mut(row.get() - 1)?;
    if row.cells.len() < cell.get() {
        row.cells.resize_with(cell.get(), Vec::new);
    }
    container(row.cells.get_mut(cell.get() - 1)?, rest)
}

/// The block of the file before at `at` in the tree `nodes`.
fn node<'t>(nodes: &'t mut [Node], at: &Address) -> Option<&'t mut Node> {
    for node in nodes {
        if node.from() == Some(at) {
            return Some(node);
        }
        if let Node::Table { rows, .. } = node {
            for cell in rows.iter_mut().flat_map(|row| row.cells.iter_mut()) {
                if let Some(found) = self::node(cell, at) {
                    return Some(found);
                }
            }
        }
    }
    None
}

/// The cell `number` of the row `row` of the file before, in the tree `body`.
fn cell<'t>(body: &'t mut [Node], row: &Address, number: usize) -> Option<&'t mut Vec<Node>> {
    let row = self::row(body, row)?;
    if row.cells.len() < number {
        row.cells.resize_with(number, Vec::new);
    }
    row.cells.get_mut(number.checked_sub(1)?)
}

/// The row `at` of the file before, in the tree `body`.
fn row<'t>(body: &'t mut [Node], at: &Address) -> Option<&'t mut Row> {
    let table = at.table_of_row()?;
    let Some(AddressStep::Row(number)) = at.steps().last() else {
        return None;
    };
    match node(body, &table)? {
        Node::Table { rows, .. } => rows.get_mut(number.get() - 1),
        Node::Paragraph { .. } => None,
    }
}

impl Node {
    /// A new paragraph with `style` and `text`.
    const fn new_paragraph(style: Option<String>, text: String) -> Self {
        Self::Paragraph {
            from: None,
            style,
            text: Some(text),
            gone: false,
            before: Vec::new(),
            after: Vec::new(),
        }
    }

    /// The address of the block of the file before, or none for a new block.
    fn from(&self) -> Option<&Address> {
        match self {
            Self::Paragraph { from, .. } | Self::Table { from, .. } => from.as_ref(),
        }
    }
}

/// Makes `outcome` in the tree `body`.
fn apply(body: &mut [Node], outcome: &Outcome) {
    match outcome {
        Outcome::Replace { at, find, with } => {
            if let Some(Node::Paragraph { text, .. }) = node(body, at) {
                *text = text
                    .take()
                    .filter(|text| text.matches(find.as_str()).count() == 1)
                    .map(|text| text.replacen(find.as_str(), with, 1));
            }
        }
        Outcome::Insert {
            at,
            place,
            text,
            style,
        } => {
            let new = Node::new_paragraph(style.clone(), text.clone());
            if let Some(Node::Paragraph { before, after, .. } | Node::Table { before, after, .. }) =
                node(body, at)
            {
                match place {
                    Place::Before => before.push(new),
                    Place::After => after.push(new),
                }
            }
        }
        Outcome::Delete { at } => delete(body, at),
        Outcome::Style { at, style } => {
            if let (Some(Node::Paragraph { style: old, .. }), Some(style)) = (node(body, at), style)
            {
                *old = Some(style.clone());
            }
        }
        Outcome::SetText { at, text, style } => set_text(body, at, text, style.as_ref()),
        Outcome::InsertRow { at, place, cells } => {
            let new = Row {
                cells: cells
                    .iter()
                    .map(|(style, text)| vec![Node::new_paragraph(style.clone(), text.clone())])
                    .collect(),
                ..Row::default()
            };
            if let Some(row) = row(body, at) {
                match place {
                    Place::Before => row.before.push(new),
                    Place::After => row.after.push(new),
                }
            }
        }
    }
}

/// Gives the paragraph `at` the text `new`, or the cell `at` one paragraph with `style` and
/// `new` in place of its blocks.
fn set_text(body: &mut [Node], at: &Address, new: &str, style: Option<&String>) {
    if let Some((row, number)) = at.row_of_cell() {
        if let Some(cell) = cell(body, &row, number.get()) {
            *cell = vec![Node::new_paragraph(style.cloned(), new.to_owned())];
        }
        return;
    }
    if let Some(Node::Paragraph { text, .. }) = node(body, at) {
        *text = Some(new.to_owned());
    }
}

/// Marks the block or the row `at` as gone.
fn delete(body: &mut [Node], at: &Address) {
    if at.table_of_row().is_some() {
        if let Some(row) = row(body, at) {
            row.gone = true;
        }
        return;
    }
    if let Some(Node::Paragraph { gone, .. } | Node::Table { gone, .. }) = node(body, at) {
        *gone = true;
    }
}

/// The expected blocks of `nodes`, the blocks of the body when `within` is none, or else of the
/// cell at that address, numbered as the new file numbers them.
fn flatten(nodes: &[Node], within: Option<&Address>, out: &mut Vec<(Address, Expected)>) {
    let (mut paragraphs, mut tables) = (0, 0);
    let mut emit = |node: &Node, out: &mut Vec<(Address, Expected)>| match node {
        Node::Paragraph { style, text, .. } => {
            paragraphs += 1;
            let step = AddressStep::Paragraph(number(paragraphs));
            out.push((
                Address::within(within, step),
                Expected::Paragraph {
                    style: style.clone(),
                    text: text.clone(),
                },
            ));
        }
        Node::Table { rows, .. } => {
            tables += 1;
            let table = Address::within(within, AddressStep::Table(number(tables)));
            let kept: Vec<&Row> = rows
                .iter()
                .flat_map(|row| {
                    row.before
                        .iter()
                        .chain((!row.gone).then_some(row))
                        .chain(row.after.iter())
                })
                .collect();
            out.push((table.clone(), Expected::Table { rows: kept.len() }));
            for (row_index, row) in kept.iter().enumerate() {
                let row_address = table.then(AddressStep::Row(number(row_index + 1)));
                for (cell_index, cell) in row.cells.iter().enumerate() {
                    let cell_address = row_address.then(AddressStep::Cell(number(cell_index + 1)));
                    flatten(cell, Some(&cell_address), out);
                }
            }
        }
    };
    for node in nodes {
        let (gone, before, after) = match node {
            Node::Paragraph {
                gone,
                before,
                after,
                ..
            }
            | Node::Table {
                gone,
                before,
                after,
                ..
            } => (*gone, before, after),
        };
        for new in before {
            emit(new, out);
        }
        if !gone {
            emit(node, out);
        }
        for new in after {
            emit(new, out);
        }
    }
}

/// The number, from 1, of the block, row or cell that `count` ends.
fn number(count: usize) -> std::num::NonZeroUsize {
    std::num::NonZeroUsize::MIN.saturating_add(count.saturating_sub(1))
}