Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
252 changes: 243 additions & 9 deletions src/office.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,7 @@ impl DocxState {
fn end_paragraph(&mut self) {
let spans = std::mem::take(&mut self.spans);
if !self.tables.is_empty() {
self.page_break = false;
if !self.cell.is_empty() {
self.cell.push('\n');
}
Expand Down Expand Up @@ -414,6 +415,7 @@ fn odf_blocks(xml: &str) -> Result<Vec<Block>, OfficeError> {
}
let content = std::mem::take(&mut text);
if !tables.is_empty() {
heading = None;
if !cell.is_empty() {
cell.push('\n');
}
Expand Down Expand Up @@ -704,18 +706,37 @@ pub(crate) fn html_blocks(html: &str) -> Vec<Block> {
row.push(text.split_whitespace().collect::<Vec<_>>().join(" "));
text.clear();
}
(h, false) if h.len() == 2 && h.starts_with('h') && h[1..].parse::<u8>().is_ok() => {
// Inside a table a heading is just cell text.
(h, false)
if !in_table
&& h.len() == 2
&& h.starts_with('h')
&& h[1..].parse::<u8>().is_ok() =>
{
flush_text(&mut text, &mut heading, in_item, &mut blocks);
heading = h[1..].parse::<u8>().ok().map(|n| n.clamp(1, 4));
}
// A heading in a cell still ends a word: `<h2>A</h2><h2>B</h2>` is "A B".
(h, _)
if in_table
&& h.len() == 2
&& h.starts_with('h')
&& h[1..].parse::<u8>().is_ok() =>
{
text.push(' ');
heading = None;
}
(h, true) if h.len() == 2 && h.starts_with('h') && h[1..].parse::<u8>().is_ok() => {
flush_text(&mut text, &mut heading, in_item, &mut blocks);
// An empty heading must not turn the next paragraph into one.
heading = None;
}
("li", false) => {
flush_text(&mut text, &mut heading, in_item, &mut blocks);
in_item = true;
}
("br", _) => text.push('\n'),
("p" | "div" | "li" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "ul" | "ol", _)
if !in_table =>
{
("p" | "div" | "li" | "ul" | "ol", _) if !in_table => {
flush_text(&mut text, &mut heading, in_item, &mut blocks);
if name == "li" && closing {
in_item = false;
Expand Down Expand Up @@ -759,6 +780,70 @@ fn decode_entities(s: &str) -> String {
out
}

/// The text encoding an RTF `\ansicpgN` names; `None` keeps the current one.
fn rtf_codepage(n: u32) -> Option<&'static encoding_rs::Encoding> {
let label = match n {
874 => "windows-874".to_owned(),
932 => "shift_jis".to_owned(),
936 => "gbk".to_owned(),
949 => "euc-kr".to_owned(),
950 => "big5".to_owned(),
1250..=1258 => format!("windows-{n}"),
10000 => "macintosh".to_owned(),
65001 => "utf-8".to_owned(),
_ => return None,
};
encoding_rs::Encoding::for_label(label.as_bytes())
}

/// RTF control words that stand for one character.
const RTF_SYMBOLS: &[(&str, char)] = &[
("lquote", '\u{2018}'),
("rquote", '\u{2019}'),
("ldblquote", '\u{201C}'),
("rdblquote", '\u{201D}'),
("endash", '\u{2013}'),
("emdash", '\u{2014}'),
("bullet", '\u{2022}'),
];

fn rtf_symbol(word: &str) -> Option<char> {
RTF_SYMBOLS
.iter()
.find(|(w, _)| *w == word)
.map(|(_, c)| *c)
}

/// Whether the last `\'hh` byte read is the lead byte of a double-byte
/// character whose trail byte is still to come. Only East Asian code pages
/// have trail bytes that can be plain ASCII letters.
fn awaits_trail_byte(bytes: &[u8], codepage: &'static encoding_rs::Encoding) -> bool {
let is_lead: fn(u8) -> bool = if codepage == encoding_rs::SHIFT_JIS {
|b| matches!(b, 0x81..=0x9F | 0xE0..=0xFC)
} else if [encoding_rs::GBK, encoding_rs::EUC_KR, encoding_rs::BIG5].contains(&codepage) {
|b| matches!(b, 0x81..=0xFE)
} else {
return false;
};
let mut i = 0;
while i < bytes.len() {
i += if is_lead(bytes[i]) { 2 } else { 1 };
}
i > bytes.len()
}

/// Decodes the `\'hh` bytes read so far, so multi-byte characters stay whole.
fn flush_rtf_bytes(
out: &mut String,
bytes: &mut Vec<u8>,
codepage: &'static encoding_rs::Encoding,
) {
if !bytes.is_empty() {
out.push_str(&codepage.decode_without_bom_handling(bytes).0);
bytes.clear();
}
}

/// Plain text from RTF: drops control words and groups such as font tables.
fn rtf_text(rtf: &str) -> String {
const SKIP_GROUPS: &[&str] = &["fonttbl", "colortbl", "stylesheet", "info", "pict", "*"];
Expand All @@ -770,7 +855,24 @@ fn rtf_text(rtf: &str) -> String {
// Fallback units after each `\uN` (`\ucN`, scoped to its group; default 1).
let mut uc = 1usize;
let mut outer_uc: Vec<usize> = Vec::new();
// `\'hh` bytes are in the document's code page (`\ansicpgN`, default 1252).
let mut codepage = encoding_rs::WINDOWS_1252;
let mut bytes: Vec<u8> = Vec::new();
while let Some(c) = chars.next() {
// An escaped lead byte may be followed by a plain ASCII trail byte
// (`\'83n` is one Shift-JIS character); it joins the pending bytes.
if matches!(c, '\x40'..='\x7E')
&& !matches!(c, '\\' | '{' | '}')
&& awaits_trail_byte(&bytes, codepage)
{
bytes.push(c as u8);
continue;
}
// Consecutive hex escapes form one character in multi-byte code
// pages, and source line breaks are not text, so neither splits them.
if !(c == '\\' && chars.peek() == Some(&'\'')) && !matches!(c, '\r' | '\n') {
flush_rtf_bytes(&mut out, &mut bytes, codepage);
}
match c {
'{' => {
depth += 1;
Expand Down Expand Up @@ -801,9 +903,13 @@ fn rtf_text(rtf: &str) -> String {
if skip_from.is_none()
&& let Ok(b) = u8::from_str_radix(&hex, 16)
{
out.push(char::from(b));
bytes.push(b);
}
}
Some('~') if skip_from.is_none() => out.push('\u{00A0}'),
Some('_') if skip_from.is_none() => out.push('\u{2011}'),
// An optional hyphen is only a line-break hint.
Some('-') => {}
Some(other) if skip_from.is_none() && !other.is_alphanumeric() => {
out.push(other)
}
Expand All @@ -827,13 +933,21 @@ fn rtf_text(rtf: &str) -> String {
if word == "uc" {
uc = param.parse().unwrap_or(1);
}
if word == "ansicpg"
&& let Some(encoding) = param.parse().ok().and_then(rtf_codepage)
{
codepage = encoding;
}
if SKIP_GROUPS.contains(&word.as_str()) && skip_from.is_none() {
skip_from = Some(depth);
}
if skip_from.is_none() {
match word.as_str() {
"par" | "line" => out.push('\n'),
"tab" => out.push('\t'),
symbol if rtf_symbol(symbol).is_some() => {
out.extend(rtf_symbol(symbol));
}
"u" => {
if let Some(ch) = param
.parse::<i32>()
Expand All @@ -844,8 +958,8 @@ fn rtf_text(rtf: &str) -> String {
}
// Skip the `\ucN` fallback units that follow a Unicode
// escape: each is one character, one `\'hh` escape (what
// Word writes) or one escaped symbol such as `\{`.
// `\uc0` means there is none.
// Word writes), one escaped symbol such as `\{`, or one
// symbol word such as `\bullet`. `\uc0` means there is none.
for _ in 0..uc {
match chars.peek() {
Some('\\') => {
Expand All @@ -854,8 +968,22 @@ fn rtf_text(rtf: &str) -> String {
let len = match ahead.peek() {
Some('\'') => 4,
Some(c) if !c.is_ascii_alphabetic() => 2,
// A control word ends the fallback.
_ => break,
_ => {
let word: String = ahead
.by_ref()
.take_while(char::is_ascii_alphabetic)
.collect();
// Other control words, such as `\par`
// or formatting, end the fallback.
if rtf_symbol(&word).is_none() {
break;
}
// The backslash, the word, and the space
// that delimits it (`take_while` ate it).
let delimiter =
chars.clone().nth(1 + word.len()) == Some(' ');
1 + word.len() + usize::from(delimiter)
}
};
chars.by_ref().take(len).for_each(drop);
}
Expand All @@ -875,6 +1003,7 @@ fn rtf_text(rtf: &str) -> String {
_ => {}
}
}
flush_rtf_bytes(&mut out, &mut bytes, codepage);
out
}

Expand Down Expand Up @@ -1237,6 +1366,40 @@ mod tests {
);
}

#[test]
fn odf_heading_in_a_table_cell_stays_in_the_cell() {
let xml = r#"<office:document-content xmlns:office="o" xmlns:text="t" xmlns:table="b"><office:body><office:text>
<table:table><table:table-row><table:table-cell><text:h text:outline-level="2">Name</text:h></table:table-cell></table:table-row></table:table>
<text:p>Body</text:p>
</office:text></office:body></office:document-content>"#;
assert_eq!(
odf_blocks(xml).expect("parse"),
vec![
Block::Table(vec![vec!["Name".into()]]),
Block::Paragraph(vec![Span::plain("Body")]),
]
);
}

#[test]
fn docx_page_break_in_a_table_cell_does_not_leak_past_the_table() {
let xml = r#"<w:document xmlns:w="w"><w:body>
<w:tbl><w:tr><w:tc><w:p><w:r><w:t>A</w:t><w:br w:type="page"/></w:r></w:p></w:tc></w:tr></w:tbl>
<w:p><w:r><w:t>Body</w:t></w:r></w:p>
</w:body></w:document>"#;
assert_eq!(
docx_blocks(xml).expect("parse"),
vec![
Block::Table(vec![vec!["A".into()]]),
Block::Paragraph(vec![Span {
text: "Body".into(),
bold: false,
italic: false,
}]),
]
);
}

#[test]
fn odf_nested_payload_hits_copy_budget_before_copying() {
let xml = format!(
Expand Down Expand Up @@ -1331,6 +1494,32 @@ mod tests {
);
}

#[test]
fn html_heading_level_does_not_outlive_its_heading() {
let body = || Block::Paragraph(vec![Span::plain("Body")]);
// An empty heading leaves nothing to style.
assert_eq!(html_blocks("<h2></h2><p>Body</p>"), vec![body()]);
// A heading in a cell is cell text, and the level stays inside it.
assert_eq!(
html_blocks("<p>Intro</p><table><tr><td><h2>Name</h2></td></tr></table><p>Body</p>"),
vec![
Block::Paragraph(vec![Span::plain("Intro")]),
Block::Table(vec![vec!["Name".into()]]),
body(),
]
);
// Headings in one cell keep a word break between them.
assert_eq!(
html_blocks("<table><tr><td><h2>Name</h2><h2>Value</h2></td></tr></table>"),
vec![Block::Table(vec![vec!["Name Value".into()]])]
);
// Markup inside a heading still keeps it a heading.
assert_eq!(
html_blocks("<h3><span>Title</span></h3><p>Body</p>"),
vec![Block::Heading(3, "Title".into()), body()]
);
}

#[test]
fn rtf_drops_control_groups() {
let rtf = r"{\rtf1\ansi{\fonttbl{\f0 Arial;}}\f0 Hello \b world\b0\par caf\'e9 \u8364?}";
Expand All @@ -1355,6 +1544,51 @@ mod tests {
assert_eq!(rtf_text(rtf), "αβCγZ");
// An escaped symbol such as `\{` is one whole fallback unit.
assert_eq!(rtf_text(r"{\rtf1\ansi\uc2\u945\'61\{Z}"), "αZ");
// So is a symbol word: `\bullet` as the fallback prints no second bullet.
assert_eq!(rtf_text(r"{\rtf1\ansi\uc1\u8226\bullet X}"), "•X");
assert_eq!(rtf_text(r"{\rtf1\ansi\uc1\u8226\bullet\par X}"), "•\nX");
// Other control words end the fallback and still apply.
assert_eq!(rtf_text(r"{\rtf1\ansi\uc1\u945\par X}"), "α\nX");
// Without a fallback, `\bullet` is text.
assert_eq!(rtf_text(r"{\rtf1\ansi\uc0\u8226\bullet X}"), "••X");
}

#[test]
fn rtf_hex_escapes_follow_the_code_page() {
// Word writes ANSI characters as bare `\'hh`; 0x80-0x9F are not Latin-1.
let rtf = r"{\rtf1\ansi\ansicpg1252 \'93Hi\'94 \'96 5\'80\'85}";
assert_eq!(
rtf_text(rtf),
"\u{201C}Hi\u{201D} \u{2013} 5\u{20AC}\u{2026}"
);
// Without `\uN`, Cyrillic text is only in the code page.
assert_eq!(rtf_text(r"{\rtf1\ansi\ansicpg1251 \'cf\'f0\'e8}"), "При");
// Multi-byte code pages: consecutive escapes are one character.
assert_eq!(rtf_text(r"{\rtf1\ansi\ansicpg932 \'82\'a0}"), "あ");
// A source line break inside a character doesn't split it.
assert_eq!(
rtf_text("{\\rtf1\\ansi\\ansicpg65001 \\'e2\n\\'82\\'ac}"),
"€"
);
// An escaped lead byte may take a plain ASCII trail byte.
assert_eq!(rtf_text(r"{\rtf1\ansi\ansicpg932 \'83n}"), "ハ");
assert_eq!(rtf_text(r"{\rtf1\ansi\ansicpg932 \'83\'6e}"), "ハ");
// Single-byte code pages never join a plain letter to an escape.
assert_eq!(rtf_text(r"{\rtf1\ansi\ansicpg1251 \'cfn}"), "Пn");
// No `\ansicpg` means Windows-1252, as Word assumes.
assert_eq!(rtf_text(r"{\rtf1\ansi caf\'e9\'92s}"), "café’s");
}

#[test]
fn rtf_symbol_words_and_control_symbols_become_text() {
let rtf =
r"{\rtf1\ansi \ldblquote a\rdblquote \lquote b\rquote \endash c\emdash \bullet d}";
// The space after a control word is its delimiter, not text.
assert_eq!(rtf_text(rtf), "“a”‘b’–c—•d");
assert_eq!(
rtf_text(r"{\rtf1 a\~b\_c co\-op}"),
"a\u{00A0}b\u{2011}c coop"
);
}

#[test]
Expand Down
Loading