f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
//! The syntax of a field code (`w:instrText` or the `w:instr` of `w:fldSimple`): its kind, its
//! arguments and its switches, in the readings that the readers of fields take today.
//!
//! The readers read an argument in three ways (word argument, quoted argument and escaped
//! argument), and some switches in any case and others only in their own case.

/// The kind of a field: the first word of its code, up to a space, in the case that the code
/// writes it. Each reader compares it in any case.
pub(crate) fn kind(code: &str) -> Option<&str> {
    code.split_whitespace().next()
}

/// Whether a field of the code `code` links as a hyperlink does: a `HYPERLINK` field, or a
/// reference (`REF`, `PAGEREF`) with the switch [`REF_LINK`].
pub(crate) fn links(code: &str) -> bool {
    let Some(kind) = kind(code) else {
        return false;
    };
    let is = |name: &str| kind.eq_ignore_ascii_case(name);
    is("HYPERLINK")
        || ((is("REF") || is("PAGEREF")) && words_after_kind(code).any(|word| REF_LINK.is(word)))
}

/// The code after its kind, from the space that ends the kind; empty for a code that holds only
/// its kind.
pub(super) fn after_kind(code: &str) -> &str {
    let code = code.trim_start();
    code.find(char::is_whitespace).map_or("", |at| &code[at..])
}

/// The words of the code after its kind, each up to a space.
pub(super) fn words_after_kind(code: &str) -> impl Iterator<Item = &str> {
    code.split_whitespace().skip(1)
}

/// Reading "word argument": a word of the code, up to a space, without the quotes at its ends.
/// A quoted argument with a space gives its first word only: `"a b"` gives `a`, and `b"` is the
/// next word.
pub(super) fn word_argument(word: &str) -> &str {
    word.trim_matches('"')
}

/// An argument of the reading "quoted argument", and the code after it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct QuotedArgument<'a> {
    /// The argument without its quotes.
    pub(super) text: &'a str,
    /// Whether the argument opens a quote that the code does not close: its text then runs to
    /// the end of the code.
    pub(super) unclosed: bool,
    /// The code after the argument: after its closing quote, or after the space that ends it.
    pub(super) rest: &'a str,
}

/// Reading "quoted argument" of the code `code`: an argument in quotes, with its spaces, up to
/// the next quote; else the argument up to the next space. No character escapes a quote: in
/// `"a \"b\""` the argument is `a \`.
pub(super) fn quoted_argument(code: &str) -> QuotedArgument<'_> {
    let code = code.trim_start();
    if let Some(inner) = code.strip_prefix('"') {
        return match inner.split_once('"') {
            Some((text, rest)) => QuotedArgument {
                text,
                unclosed: false,
                rest,
            },
            None => QuotedArgument {
                text: inner,
                unclosed: true,
                rest: "",
            },
        };
    }
    let (text, rest) = code.split_once(char::is_whitespace).unwrap_or((code, ""));
    QuotedArgument {
        text,
        unclosed: false,
        rest,
    }
}

/// Reading "escaped argument" of the code `code`: an argument in quotes up to the next quote,
/// else up to the next space, in which a backslash takes the character after it as it is, a
/// quote or a space too: `"a \"b\""` gives `a "b"`. In an argument without quotes, a quote is
/// part of the argument.
pub(super) fn escaped_argument(code: &str) -> String {
    let code = code.trim_start();
    let mut chars = code.chars();
    let quoted = code.starts_with('"');
    if quoted {
        chars.next();
    }
    let mut out = String::new();
    while let Some(ch) = chars.next() {
        match ch {
            '\\' => out.extend(chars.next()),
            '"' if quoted => break,
            ch if ch.is_whitespace() && !quoted => break,
            ch => out.push(ch),
        }
    }
    out
}

/// How a reader compares a word of a field code with the name of a switch.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SwitchCase {
    /// Only in the case of the name: `\n` and not `\N`.
    Exact,
    /// In any case of its ASCII letters: `\p` and `\P`.
    AnyCase,
}

/// A switch of a field code that a reader knows, with the case in which the reader reads it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Switch {
    /// The switch as a code writes it, with its backslash.
    name: &'static str,
    /// How a word compares with the name.
    case: SwitchCase,
}

impl Switch {
    /// Whether the word `word` of a code is this switch.
    pub(super) fn is(self, word: &str) -> bool {
        match self.case {
            SwitchCase::Exact => word == self.name,
            SwitchCase::AnyCase => word.eq_ignore_ascii_case(self.name),
        }
    }

    /// The code after the first place of this switch in `code`, in the case of its name. It
    /// finds the switch anywhere, also inside a quoted argument and inside a word.
    ///
    /// It does not read the switch's case rule, so use it only for a switch whose name has no
    /// letter, such as `\@`, where both rules find the same places. An `AnyCase` switch with a
    /// letter would be found in the case of its name only.
    pub(super) fn after_first(self, code: &str) -> Option<&str> {
        code.split_once(self.name).map(|(_, rest)| rest)
    }
}

/// `\*`, the format of the result, of `REF` and `STYLEREF`, followed by the format's name.
pub(super) const FORMAT: Switch = Switch {
    name: "\\*",
    case: SwitchCase::Exact,
};

/// `\@`, the date and time picture of `DATE`, `TIME`, `SAVEDATE`, `PRINTDATE` and
/// `DOCPROPERTY`, which `fields::picture_switch` finds anywhere in the code
/// ([`Switch::after_first`]).
pub(super) const PICTURE: Switch = Switch {
    name: "\\@",
    case: SwitchCase::Exact,
};

/// `\n` of `REF`: the paragraph number of the bookmark in its own pattern.
pub(super) const REF_PATTERN: Switch = Switch {
    name: "\\n",
    case: SwitchCase::Exact,
};

/// `\r` of `REF`: the paragraph number relative to the field's place.
pub(super) const REF_RELATIVE: Switch = Switch {
    name: "\\r",
    case: SwitchCase::Exact,
};

/// `\w` of `REF`: the paragraph number in full.
pub(super) const REF_FULL: Switch = Switch {
    name: "\\w",
    case: SwitchCase::Exact,
};

/// `\h` of `REF`: the result is a link to the bookmark.
pub(super) const REF_LINK: Switch = Switch {
    name: "\\h",
    case: SwitchCase::Exact,
};

/// `\p` of `PAGEREF`: "above" or "below" in place of the page number.
pub(super) const PAGE_POSITION: Switch = Switch {
    name: "\\p",
    case: SwitchCase::AnyCase,
};

/// `\l` of `STYLEREF`: the last paragraph of the style on the page, not the first.
pub(super) const STYLE_LAST: Switch = Switch {
    name: "\\l",
    case: SwitchCase::AnyCase,
};

/// `\n` of `STYLEREF`: the paragraph number of the paragraph found, not its text.
pub(super) const STYLE_NUMBER: Switch = Switch {
    name: "\\n",
    case: SwitchCase::AnyCase,
};

/// The kind of a drop-down form field, which shows the entry that its list selects.
pub(super) const FORM_DROP_DOWN: &str = "FORMDROPDOWN";

/// The kind of a text form field.
pub(super) const FORM_TEXT: &str = "FORMTEXT";

/// `\r` of `ADVANCE`: the text after the field moves right by a number of points.
pub(super) const ADVANCE_RIGHT: Switch = Switch {
    name: "\\r",
    case: SwitchCase::AnyCase,
};

/// `\l` of `ADVANCE`: the text after the field moves left by a number of points.
pub(super) const ADVANCE_LEFT: Switch = Switch {
    name: "\\l",
    case: SwitchCase::AnyCase,
};

/// The format `\* MERGEFORMAT`, which keeps the format of the result when the field updates.
pub(super) const MERGE_FORMAT: &str = "MERGEFORMAT";

/// The format `\* CHARFORMAT`, which gives the result the format of the field's kind.
pub(super) const CHAR_FORMAT: &str = "CHARFORMAT";

/// Whether the word `word` after `\*` is one of the format names `names`, in any case.
pub(super) fn is_format(word: &str, names: &[&str]) -> bool {
    names.iter().any(|name| word.eq_ignore_ascii_case(name))
}

#[cfg(test)]
mod tests {
    use super::{
        FORMAT, PAGE_POSITION, PICTURE, QuotedArgument, REF_FULL, REF_LINK, REF_PATTERN,
        REF_RELATIVE, STYLE_LAST, after_kind, escaped_argument, kind, quoted_argument,
        word_argument, words_after_kind,
    };

    #[test]
    fn the_three_readings_of_an_argument_differ_on_quotes_spaces_and_backslashes() {
        // The text after a kind, and what each reading gives: the word argument of its first
        // word, the quoted argument (text, unclosed, rest) and the escaped argument.
        let cases = [
            // A quoted argument with a space: the word argument keeps the first word.
            (r#" "a b" \n"#, "a", ("a b", false, r" \n"), "a b"),
            // An escaped quote: only the escaped argument reads past it.
            (
                r#" "a \"b\" c""#,
                "a",
                (r"a \", false, r#"b\" c""#),
                r#"a "b" c"#,
            ),
            // A quote that the code does not close.
            (r#" "a b"#, "a", ("a b", true, ""), "a b"),
            // A word after the closing quote: the word argument keeps it.
            (r#" "a"b c"#, r#"a"b"#, ("a", false, "b c"), "a"),
            // A backslash before a space joins two words in the escaped argument only.
            (r" a\ b", r"a\", (r"a\", false, "b"), "a b"),
            // A word with no quote and no backslash reads alike in each.
            (" plain rest", "plain", ("plain", false, "rest"), "plain"),
        ];
        for (code, word, (text, unclosed, rest), escaped) in cases {
            assert_eq!(
                words_after_kind(&format!("KIND{code}"))
                    .next()
                    .map(word_argument),
                Some(word),
                "{code}"
            );
            assert_eq!(
                quoted_argument(code),
                QuotedArgument {
                    text,
                    unclosed,
                    rest
                },
                "{code}"
            );
            assert_eq!(escaped_argument(code), escaped, "{code}");
        }
    }

    #[test]
    fn reads_the_kind_and_the_code_after_it() {
        assert_eq!(kind("  toc \\o \"1-3\""), Some("toc"));
        assert_eq!(kind("   "), None);
        assert_eq!(after_kind("  STYLEREF  Heading"), "  Heading");
        assert_eq!(after_kind(" PAGE"), "");
    }

    #[test]
    fn reads_each_switch_in_its_case() {
        // (switch, word, whether the word is the switch)
        let cases = [
            (REF_PATTERN, r"\n", true),
            (REF_PATTERN, r"\N", false),
            (REF_RELATIVE, r"\R", false),
            (REF_FULL, r"\W", false),
            (REF_LINK, r"\H", false),
            (FORMAT, r"\*", true),
            (FORMAT, r"\**", false),
            (PAGE_POSITION, r"\P", true),
            (PAGE_POSITION, r"\p", true),
            (STYLE_LAST, r"\L", true),
            (STYLE_LAST, r"\l", true),
            (STYLE_LAST, r"\n", false),
        ];
        for (switch, word, is) in cases {
            assert_eq!(switch.is(word), is, "{switch:?} {word}");
        }
    }

    #[test]
    fn finds_the_picture_switch_anywhere_also_inside_a_quoted_argument() {
        assert_eq!(
            PICTURE.after_first(r#"DOCPROPERTY "x \@ y""#),
            Some(r#" y""#)
        );
        assert_eq!(PICTURE.after_first(r#"DATE\@"yyyy""#), Some(r#""yyyy""#));
        assert_eq!(PICTURE.after_first("DATE"), None);
    }
}