f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
//! The named edits of the rows and the cells of a table, and of all the text of a paragraph: a
//! new row next to a row, and new text in place of the content of a paragraph or a cell.

use std::fmt::Write as _;
use std::ops::Range;

use f_office_xml::NodeId;

use super::build::{
    content_after, copy_children, first_run_properties, holds_note_reference_in, insert_last,
    open_range_in, prefix, run_text,
};
use super::{Main, NamedFault, Place};
use crate::ns::W;
use crate::reader::PartReader;
use crate::table::{Merge, RowCell, row_cells};

/// The properties that a copy leaves out: the conditional formatting that Word records for a
/// row, a cell or a paragraph (`w:cnfStyle`), which the table style gives again; the section
/// break of a paragraph; and the vertical merge of a cell, which the new cell writes itself. A
/// file with tracked changes takes no named edit, so no change element is left to copy.
const NOT_COPIED: [&str; 3] = ["cnfStyle", "sectPr", "vMerge"];

/// A new row: its XML, and the style and the text of the one paragraph of each of its cells.
pub(super) struct NewRow {
    pub(super) xml: String,
    pub(super) cells: Vec<(Option<String>, String)>,
}

/// The new row of an insert at `place` of the row `row`, whose next row is `next`, with
/// `texts` in its first cells.
pub(super) fn new_row(
    main: &Main<'_>,
    reader: &mut PartReader,
    (row, place, next): (NodeId, Place, Option<NodeId>),
    texts: &[String],
) -> Result<NewRow, NamedFault> {
    let doc = main.doc;
    let places = row_cells(reader, row);
    if places
        .iter()
        .any(|cell| main.parent(cell.node) != Some(row))
    {
        return Err(NamedFault::WrappedCells);
    }
    if texts.len() > places.len() {
        return Err(NamedFault::TooManyCells {
            given: texts.len(),
            cells: places.len(),
        });
    }
    let below = next.map_or_default(|next| row_cells(reader, next));
    let w = prefix(doc, row)?;
    let mut cells_xml = String::new();
    let mut cells = Vec::new();
    for (index, place_of_cell) in places.iter().enumerate() {
        let continues = continues_merge(place_of_cell, place, &below);
        let text = texts.get(index).map_or("", String::as_str);
        if continues && !text.is_empty() {
            return Err(NamedFault::MergedCellText { cell: index + 1 });
        }
        let (xml, style) = new_cell(main, &w, place_of_cell.node, continues, text);
        cells_xml.push_str(&xml);
        cells.push((style, text.to_owned()));
    }
    let exceptions = copied(main, row, "tblPrEx", &w);
    let properties = copied(main, row, "trPr", &w);
    Ok(NewRow {
        xml: format!("<{w}:tr>{exceptions}{properties}{cells_xml}</{w}:tr>"),
        cells,
    })
}

/// Whether the new cell at the place of the cell `cell` continues its vertical merge: after the
/// row, when the cell takes part in a merge that the cell at its grid column in the next row
/// `below` continues; before the row, when the cell continues a merge.
fn continues_merge(cell: &RowCell, place: Place, below: &[RowCell]) -> bool {
    match place {
        Place::Before => cell.merge == Some(Merge::Continue),
        Place::After => {
            cell.merge.is_some()
                && below
                    .iter()
                    .any(|next| next.start == cell.start && next.merge == Some(Merge::Continue))
        }
    }
}

/// The new cell at the place of the cell `cell`, with its properties, a `w:vMerge` when it
/// `continues` a merge, and one paragraph with the properties of the cell's first paragraph and
/// `text` in the formatting of that paragraph's first run; with the style of the paragraph.
fn new_cell(
    main: &Main<'_>,
    w: &str,
    cell: NodeId,
    continues: bool,
    text: &str,
) -> (String, Option<String>) {
    let mut properties = main
        .doc
        .child(cell, W, "tcPr")
        .map_or_default(|tcpr| copy_children(main, tcpr, &|child| not_copied(main, child)));
    if continues {
        let _ = write!(properties, "<{w}:vMerge/>");
    }
    let properties = wrapped(w, "tcPr", &properties);
    let (paragraph, style) = one_paragraph(main, w, cell, text);
    (format!("<{w}:tc>{properties}{paragraph}</{w}:tc>"), style)
}

/// One paragraph with the properties of the first paragraph of the cell `cell` and `text` in
/// the formatting of that paragraph's first run, and the style of the paragraph.
fn one_paragraph(main: &Main<'_>, w: &str, cell: NodeId, text: &str) -> (String, Option<String>) {
    let doc = main.doc;
    let first = doc.child(cell, W, "p");
    let ppr = first.and_then(|paragraph| doc.child(paragraph, W, "pPr"));
    let style = ppr
        .and_then(|ppr| doc.child(ppr, W, "pStyle"))
        .and_then(|style| doc.attribute(style, Some(W), "val"))
        .map(str::to_owned);
    let properties =
        ppr.map_or_default(|ppr| copy_children(main, ppr, &|child| not_copied(main, child)));
    let properties = wrapped(w, "pPr", &properties);
    let run = run(main, w, first, text);
    (format!("<{w}:p>{properties}{run}</{w}:p>"), style)
}

/// A run with `text` in the formatting of the first run of `paragraph`; nothing for no text.
fn run(main: &Main<'_>, w: &str, paragraph: Option<NodeId>, text: &str) -> String {
    if text.is_empty() {
        return String::new();
    }
    let formatting = paragraph
        .and_then(|paragraph| first_run_properties(main, paragraph))
        .unwrap_or_default();
    format!("<{w}:r>{formatting}{}</{w}:r>", run_text(w, text))
}

/// The child `local` of `node` written again without the properties that a copy leaves out.
fn copied(main: &Main<'_>, node: NodeId, local: &str, w: &str) -> String {
    main.doc
        .child(node, W, local)
        .map_or_else(String::new, |child| {
            wrapped(
                w,
                local,
                &copy_children(main, child, &|grandchild| not_copied(main, grandchild)),
            )
        })
}

/// `inner` in an element `local`, or nothing when `inner` is empty.
fn wrapped(w: &str, local: &str, inner: &str) -> String {
    if inner.is_empty() {
        String::new()
    } else {
        format!("<{w}:{local}>{inner}</{w}:{local}>")
    }
}

/// Whether a copy leaves out the property `node`.
fn not_copied(main: &Main<'_>, node: NodeId) -> bool {
    NOT_COPIED.iter().any(|local| main.doc.is(node, W, local))
}

/// The splice of a set-text of the paragraph or the cell `node`, whose properties are its child
/// `properties` (`w:pPr` or `w:tcPr`): the content after them, replaced by `xml`. Fails for
/// content that holds one end of a range, and says whether it held a note's reference.
pub(super) fn replaced_content(
    main: &Main<'_>,
    node: NodeId,
    properties: &str,
    xml: &str,
) -> Result<((Range<usize>, String), bool), NamedFault> {
    let doc = main.doc;
    let removed: Vec<NodeId> = doc
        .child_elements(node)
        .filter(|&child| !doc.is(child, W, properties))
        .collect();
    if let Some(element) = open_range_in(doc, &removed) {
        return Err(NamedFault::RangeEnd { element });
    }
    let notes = holds_note_reference_in(doc, &removed);
    let span = main.span(node);
    let kept = doc.child(node, W, properties).map(|child| main.span(child));
    let splice = match content_after(main.bytes, &span, kept) {
        Some(content) => (content, xml.to_owned()),
        None => insert_last(main.bytes, span, xml),
    };
    Ok((splice, notes))
}

/// The content of a set-text: of a paragraph, one run with `text`, and of a cell, one paragraph
/// as [`one_paragraph`] makes it; with the style of the cell's paragraph.
pub(super) fn new_content(
    main: &Main<'_>,
    (node, cell): (NodeId, bool),
    text: &str,
) -> Result<(String, Option<String>), NamedFault> {
    let w = prefix(main.doc, node)?;
    if cell {
        return Ok(one_paragraph(main, &w, node, text));
    }
    Ok((run(main, &w, Some(node), text), None))
}