PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M10: Markdown emphasis follows CommonMark's rules at run boundaries, and the export has a parity entry (#1595)
Adrian20d396d180a3
diff --git a/crates/export/src/as_markdown.rs b/crates/export/src/as_markdown.rsindex 0d2657f55..a5c986c6b 100644--- a/crates/export/src/as_markdown.rs+++ b/crates/export/src/as_markdown.rs@@ -32,25 +32,71 @@ fn block_start(line: String) -> String {}}-/// `text` (already escaped) in bold and/or italic. The markers go around the text without its-/// outer spaces, which Markdown would not read as emphasis.-pub(crate) fn emphasis(text: &str, bold: bool, italic: bool) -> String {+/// `text` (already escaped) in bold and/or italic, its outer spaces kept outside. `open` and+/// `close` say whether `*` markers would be read as emphasis on that side (see [`marks`]);+/// where they would not, as in `foo` + bold `.` + `bar`, the run is wrapped in HTML tags, which+/// CommonMark takes inline. The text's own outer spaces count as a side that marks.+pub(crate) fn emphasis(text: &str, bold: bool, italic: bool, open: bool, close: bool) -> String {let core = text.trim();if core.is_empty() || !(bold || italic) {return text.to_string();}let lead = text.get(..text.len().saturating_sub(text.trim_start().len())).unwrap_or_default();let trail = text.get(text.trim_end().len()..).unwrap_or_default();- let mark = match (bold, italic) {- (true, true) => "***",- (true, false) => "**",- _ => "*",+ let markers = (open || !lead.is_empty()) && (close || !trail.is_empty());+ let (before, after) = match (markers, bold, italic) {+ (true, true, true) => ("***", "***"),+ (true, true, false) => ("**", "**"),+ (true, false, _) => ("*", "*"),+ (false, true, true) => ("<strong><em>", "</em></strong>"),+ (false, true, false) => ("<strong>", "</strong>"),+ (false, false, _) => ("<em>", "</em>"),};- format!("{lead}{mark}{core}{mark}{trail}")+ format!("{lead}{before}{core}{after}{trail}")+}++/// A paragraph's runs (text, bold, italic) as one line of Markdown. Neighbouring runs in the+/// same style are joined first, so two bold runs never meet as `****`.+pub(crate) fn paragraph(runs: &[(&str, bool, bool)]) -> String {+ let mut merged: Vec<(String, bool, bool)> = Vec::new();+ for &(text, bold, italic) in runs {+ match merged.last_mut() {+ Some(last) if last.1 == bold && last.2 == italic => last.0.push_str(text),+ _ => merged.push((text.to_string(), bold, italic)),+ }+ }+ let texts: Vec<String> = merged.iter().map(|(text, ..)| md_text(text)).collect();+ let mut out = String::new();+ for (k, ((_, bold, italic), text)) in merged.iter().zip(&texts).enumerate() {+ let core = text.trim();+ let open = marks(core.chars().next(), out.chars().last());+ // Markers of a styled neighbour right next to these would join them into one run.+ let close = match (merged.get(k.saturating_add(1)), texts.get(k.saturating_add(1))) {+ (Some((_, b, i)), Some(next)) if (*b || *i) && !next.starts_with(char::is_whitespace) => false,+ (_, next) => marks(core.chars().last(), next.and_then(|n| n.chars().next())),+ };+ out.push_str(&emphasis(text, *bold, *italic, open, close));+ }+ out+}++/// Whether a `*` marker between the text's `edge` character and the `outside` one is read as+/// emphasis (CommonMark's flanking rules for `*`): always next to a space or the line's edge,+/// never next to another `*`, and otherwise unless the text's edge is punctuation while the+/// outside is a letter or digit.+fn marks(edge: Option<char>, outside: Option<char>) -> bool {+ match (edge, outside) {+ (_, None) => true,+ (_, Some(o)) if o.is_whitespace() => true,+ (_, Some('*')) => false,+ (Some(e), Some(o)) => e.is_alphanumeric() || o.is_ascii_punctuation(),+ (None, Some(_)) => false,+ }}fn cell(c: &Cell) -> String {- emphasis(&md_text(&c.text), c.bold, c.italic)+ // A cell sits between `| ` and ` |`, so its markers always have a space outside.+ emphasis(&md_text(&c.text), c.bold, c.italic, true, true)}/// Markdown (CommonMark, with GitHub's pipe tables): headings, paragraphs with bold and italic,@@ -61,7 +107,8 @@ pub fn markdown(pages: &[Page]) -> String {match it {Item::Para(runs, lvl) => {// A heading's weight is the heading's own, as in the HTML export.- let text: String = runs.iter().map(|r| emphasis(&md_text(&r.text), r.block.bold && lvl == 0, r.block.italic)).collect();+ let runs: Vec<(&str, bool, bool)> = runs.iter().map(|r| (r.text.as_str(), r.block.bold && lvl == 0, r.block.italic)).collect();+ let text = paragraph(&runs);let text = text.trim();if text.is_empty() {continue;diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rsindex 54d8500a9..db53ee59c 100644--- a/crates/export/src/lib.rs+++ b/crates/export/src/lib.rs@@ -30,9 +30,9 @@ pub(crate) use as_html::esc;pub use as_html::html;#[cfg(test)]use as_html::{allowed, base64};-#[cfg(test)]-use as_markdown::emphasis;pub use as_markdown::markdown;+#[cfg(test)]+use as_markdown::{emphasis, paragraph};pub use as_rtf::rtf;pub use layout::{Block, Cell, Image, Page, Table};#[cfg(test)]diff --git a/crates/export/src/tests.rs b/crates/export/src/tests.rsindex be4708da4..27cd8264e 100644--- a/crates/export/src/tests.rs+++ b/crates/export/src/tests.rs@@ -819,9 +819,18 @@ fn markdown_escapes_markup_and_keeps_emphasis_and_tables() {assert!(md.contains("\\*stars\\* \\_under\\_ \\`tick\\` \\[link\\](x) a\\|b \\# \\#tag next"), "{md}");assert!(md.contains("**Strong words in a sentence of their own.**"), "{md}");// Markdown reads no emphasis where a marker sits next to a space: the outer spaces go outside.- assert_eq!(emphasis(" two words ", true, false), " **two words** ");- assert_eq!(emphasis("both", true, true), "***both***");- assert_eq!(emphasis(" ", true, true), " ", "nothing to mark");+ assert_eq!(emphasis(" two words ", true, false, false, false), " **two words** ");+ assert_eq!(emphasis("both", true, true, true, true), "***both***");+ assert_eq!(emphasis(" ", true, true, true, true), " ", "nothing to mark");+ // Runs in one style are one: two bold runs side by side don't meet as `****`.+ assert_eq!(paragraph(&[("hello", true, false), ("world", true, false)]), "**helloworld**");+ // Markers inside a word would stay literal in CommonMark, so a run there gets HTML tags.+ assert_eq!(paragraph(&[("foo", false, false), (".", true, false), ("bar", false, false)]), "foo<strong>.</strong>bar");+ assert_eq!(paragraph(&[("x", true, false), ("y", false, true)]), "<strong>x</strong>*y*", "two styles side by side");+ // `*` may sit inside a word, and before punctuation that follows a letter.+ assert_eq!(paragraph(&[("foo", false, false), ("bar", true, false), ("baz", false, false)]), "foo**bar**baz");+ assert_eq!(paragraph(&[("a ", false, false), ("b", true, false), (" c", false, false)]), "a **b** c");+ assert_eq!(paragraph(&[("say ", false, false), ("this", false, true), (", then", false, false)]), "say *this*, then");assert!(md.contains("*slanted*"), "{md}");assert!(!md.chars().any(|c| !allowed(c)), "{md:?}");diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.tomlindex 47ac06fdd..3ba6f85cf 100644--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@ -7067,6 +7067,18 @@ tools = ["doc_export_office"]evidence = ["crates/export/src/tests.rs::table_spans_do_not_consume_text_they_do_not_emit", "crates/export/src/tests.rs::rtf_escapes_and_sizes", "crates/export/src/tests.rs::text_colour_survives_every_format", "crates/export/src/tests.rs::word_opens_text_with_control_characters_and_long_pages", "crates/automation/tests/it/automation.rs::exporting_to_word_html_and_rtf", "crates/ui-egui/tests/it/compare.rs::export_to_word_html_and_rtf"]notes = "Text in slots covered by a preceding table-cell span remains in paragraph flow instead of being discarded. Paragraphs with sizes, bold, italic, text colour (colortbl), Unicode; a block that continues another on its line is a formatted group inside that paragraph (#4158), though a style change that wraps onto the next line still splits it; page breaks. Images are left out."++[[feature]]+id = "create.export-markdown"+title = "Export to Markdown"+area = "J"+tier = "P3"+milestone = "M10"+status = "partial"+commands = []+tools = ["doc_export_office"]+evidence = ["crates/export/src/tests.rs::markdown_has_headings_paragraphs_and_page_rules_in_order", "crates/export/src/tests.rs::markdown_escapes_markup_and_keeps_emphasis_and_tables", "crates/automation/tests/it/automation.rs::exporting_to_word_html_and_rtf"]+notes = "Requested in #1595; not an Acrobat export. doc_export_office with a .md or .markdown path writes CommonMark with GitHub pipe tables: headings (levels 1 to 6), paragraphs with bold and italic (as HTML tags where Markdown's markers would not be read as emphasis), tables with their first row as the header, and a rule between pages; text Markdown would read as markup is escaped. Missing: a menu item, images, lists and links (the export's layout model has none of the last two), and text colour."[[feature]]id = "create.export-xlsx"title = "Export to Excel (.xlsx) with table detection"