use std::collections::HashMap;
use std::num::NonZeroUsize;
use crate::{
Address, AddressStep, Document, LinkTarget, StoryLink, StoryParagraph, TextBlock,
TextBlockKind, TextStory,
};
const OBJECT_REPLACEMENT: char = '\u{FFFC}';
impl Document {
#[must_use]
pub fn to_plain_text(&self) -> String {
export_body(self, Format::PlainText)
}
#[must_use]
pub fn to_markdown(&self) -> String {
export_body(self, Format::Markdown)
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Format {
PlainText,
Markdown,
}
fn export_body(doc: &Document, format: Format) -> String {
let story = doc.story_text(TextStory::Body);
let stories: HashMap<&Address, &StoryParagraph> = story
.iter()
.filter_map(|p| p.address.as_ref().map(|addr| (addr, p)))
.collect();
let blocks = doc.text_blocks();
let mut parts: Vec<String> = Vec::new();
let mut idx = 0;
while let Some(block) = blocks.get(idx) {
if let Some(table_num) = top_table_number(block) {
let (table_text, next_idx) =
collect_table(blocks, idx + 1, table_num, &stories, format);
if !table_text.is_empty() {
parts.push(table_text);
}
idx = next_idx;
continue;
}
if let Some(rendered) = render_paragraph(block, &stories, format) {
parts.push(rendered);
}
idx += 1;
}
if parts.is_empty() {
String::new()
} else {
let mut out = parts.join("\n\n");
out.push('\n');
out
}
}
fn top_table_number(block: &TextBlock) -> Option<NonZeroUsize> {
if !matches!(block.kind, TextBlockKind::Table { .. }) {
return None;
}
match block.address.steps() {
[AddressStep::Table(num)] => Some(*num),
_ => None,
}
}
fn table_cell_coords(block: &TextBlock, table_num: NonZeroUsize) -> Option<(usize, usize)> {
match block.address.steps() {
[
AddressStep::Table(t),
AddressStep::Row(r),
AddressStep::Cell(c),
..,
] if *t == table_num => Some((r.get() - 1, c.get() - 1)),
_ => None,
}
}
fn collect_table(
blocks: &[TextBlock],
start: usize,
table_num: NonZeroUsize,
stories: &HashMap<&Address, &StoryParagraph>,
format: Format,
) -> (String, usize) {
let mut grid: Vec<Vec<String>> = Vec::new();
let mut idx = start;
while let Some(block) = blocks.get(idx) {
let Some((row_idx, col_idx)) = table_cell_coords(block, table_num) else {
break;
};
if let Some(text) = paragraph_text(block, stories, format) {
append_cell(&mut grid, row_idx, col_idx, &text, format);
}
idx += 1;
}
let rendered = match format {
Format::PlainText => format_plain_table(&grid),
Format::Markdown => format_markdown_table(&grid),
};
(rendered, idx)
}
fn append_cell(
grid: &mut Vec<Vec<String>>,
row_idx: usize,
col_idx: usize,
text: &str,
format: Format,
) {
if grid.len() <= row_idx {
grid.resize_with(row_idx + 1, Vec::new);
}
let Some(row) = grid.get_mut(row_idx) else {
return;
};
if row.len() <= col_idx {
row.resize_with(col_idx + 1, String::new);
}
let Some(cell) = row.get_mut(col_idx) else {
return;
};
if !cell.is_empty() {
cell.push_str(if format == Format::Markdown {
"<br>"
} else {
" "
});
}
cell.push_str(text);
}
fn format_plain_table(grid: &[Vec<String>]) -> String {
let mut lines: Vec<String> = Vec::with_capacity(grid.len());
for row in grid {
let joined = row
.iter()
.map(|c| c.replace('\n', " "))
.collect::<Vec<_>>()
.join("\t");
if !joined.trim().is_empty() {
lines.push(joined);
}
}
lines.join("\n")
}
fn format_markdown_table(grid: &[Vec<String>]) -> String {
let cols = grid.iter().map(Vec::len).max().unwrap_or(0);
if cols == 0 || grid.is_empty() {
return String::new();
}
let mut lines: Vec<String> = Vec::with_capacity(grid.len() + 1);
for (row_idx, row) in grid.iter().enumerate() {
lines.push(format_markdown_row(row, cols));
if row_idx == 0 {
let sep: Vec<&str> = vec!["---"; cols];
lines.push(format!("| {} |", sep.join(" | ")));
}
}
lines.join("\n")
}
fn format_markdown_row(row: &[String], cols: usize) -> String {
let mut cells: Vec<String> = Vec::with_capacity(cols);
for col_idx in 0..cols {
let raw = row.get(col_idx).map_or("", String::as_str);
cells.push(raw.replace('|', "\\|").replace('\n', "<br>"));
}
format!("| {} |", cells.join(" | "))
}
fn render_paragraph(
block: &TextBlock,
stories: &HashMap<&Address, &StoryParagraph>,
format: Format,
) -> Option<String> {
let text = paragraph_text(block, stories, format)?;
if format == Format::Markdown
&& let Some(level) = block.outline_level
{
let hashes = "#".repeat((usize::from(level) + 1).min(6));
let heading = text.replace('\n', " ");
return Some(format!("{hashes} {}", heading.trim()));
}
Some(text)
}
fn paragraph_text(
block: &TextBlock,
stories: &HashMap<&Address, &StoryParagraph>,
format: Format,
) -> Option<String> {
let TextBlockKind::Paragraph { text: fallback, .. } = &block.kind else {
return None;
};
let story_text = stories.get(&block.address).and_then(|story| {
let rendered = if format == Format::Markdown {
render_markdown_links(&story.text, &story.links)
} else {
clean_story_text(&story.text)
};
(!rendered.trim().is_empty()).then_some(rendered)
});
let text = story_text.unwrap_or_else(|| fallback.clone());
if text.trim().is_empty() {
None
} else {
Some(text)
}
}
fn clean_story_text(raw: &str) -> String {
raw.replace(OBJECT_REPLACEMENT, "")
}
fn render_markdown_links(raw: &str, links: &[StoryLink]) -> String {
if links.is_empty() {
return clean_story_text(raw);
}
let mut out = String::with_capacity(raw.len());
let mut cursor = 0usize;
for link in links {
let LinkTarget::External(url) = &link.target else {
continue;
};
let start = link.start_byte as usize;
let end = link.end_byte as usize;
if start < cursor || end <= start || end > raw.len() {
continue;
}
let (Some(before), Some(label)) = (raw.get(cursor..start), raw.get(start..end)) else {
continue;
};
out.push_str(&clean_story_text(before));
let clean_label = clean_story_text(label);
if clean_label.trim().is_empty() {
out.push_str(&clean_label);
} else {
out.push('[');
out.push_str(&clean_label);
out.push_str("](");
out.push_str(url);
out.push(')');
}
cursor = end;
}
if let Some(tail) = raw.get(cursor..) {
out.push_str(&clean_story_text(tail));
}
out
}
#[cfg(test)]
mod tests {
use std::io::Write as _;
use crate::{Document, FontDatabase, Options};
fn minimal_docx(body: &str) -> Vec<u8> {
let mut buf = std::io::Cursor::new(Vec::new());
{
let mut zip = zip::ZipWriter::new(&mut buf);
let opts = zip::write::SimpleFileOptions::default();
zip.start_file("[Content_Types].xml", opts).ok();
let _ = zip.write_all(
br#"<?xml version="1.0" encoding="UTF-8"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>
</Types>"#,
);
zip.start_file("_rels/.rels", opts).ok();
let _ = zip.write_all(
br#"<?xml version="1.0" encoding="UTF-8"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>"#,
);
zip.start_file("word/_rels/document.xml.rels", opts).ok();
let _ = zip.write_all(
br#"<?xml version="1.0" encoding="UTF-8"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://f-office.org" TargetMode="External"/>
</Relationships>"#,
);
zip.start_file("word/styles.xml", opts).ok();
let _ = zip.write_all(
br#"<?xml version="1.0" encoding="UTF-8"?>
<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:style w:type="paragraph" w:styleId="Heading1">
<w:name w:val="heading 1"/>
<w:pPr><w:outlineLvl w:val="0"/></w:pPr>
</w:style>
</w:styles>"#,
);
zip.start_file("word/document.xml", opts).ok();
let xml = format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<w:body>{body}</w:body>
</w:document>"#
);
let _ = zip.write_all(xml.as_bytes());
}
buf.into_inner()
}
#[test]
fn exports_headings_paragraphs_links_and_tables_to_plain_text_and_markdown()
-> Result<(), crate::Error> {
let body = concat!(
r#"<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Quarterly Report</w:t></w:r></w:p>"#,
r#"<w:p><w:r><w:t xml:space="preserve">Visit </w:t></w:r><w:hyperlink r:id="rId2"><w:r><w:t>F-Office</w:t></w:r></w:hyperlink><w:r><w:t>.</w:t></w:r></w:p>"#,
r#"<w:tbl><w:tr><w:tc><w:p><w:r><w:t>Metric</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>Value</w:t></w:r></w:p></w:tc></w:tr>"#,
r#"<w:tr><w:tc><w:p><w:r><w:t>Pages</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>42</w:t></w:r></w:p></w:tc></w:tr></w:tbl>"#
);
let bytes = minimal_docx(body);
let fonts = FontDatabase::new();
let doc = Document::open(&bytes, &fonts, &Options::default())?.value;
let plain = doc.to_plain_text();
assert_eq!(
plain,
"Quarterly Report\n\nVisit F-Office.\n\nMetric\tValue\nPages\t42\n"
);
let md = doc.to_markdown();
assert!(md.contains("# Quarterly Report\n\n"), "md={md:?}");
assert!(
md.contains("| Metric | Value |\n| --- | --- |\n| Pages | 42 |"),
"md={md:?}"
);
Ok(())
}
}