1use std::collections::HashMap;
4use std::num::NonZeroUsize;
5
6use crate::{
7 Address, AddressStep, Document, LinkTarget, StoryLink, StoryParagraph, TextBlock,
8 TextBlockKind, TextStory,
9};
10
11const OBJECT_REPLACEMENT: char = '\u{FFFC}';
12
13impl Document {
14 #[must_use]
17 pub fn to_plain_text(&self) -> String {
18 export_body(self, Format::PlainText)
19 }
20
21 #[must_use]
24 pub fn to_markdown(&self) -> String {
25 export_body(self, Format::Markdown)
26 }
27}
28
29#[derive(Clone, Copy, PartialEq, Eq)]
30enum Format {
31 PlainText,
32 Markdown,
33}
34
35fn export_body(doc: &Document, format: Format) -> String {
36 let story = doc.story_text(TextStory::Body);
37 let stories: HashMap<&Address, &StoryParagraph> = story
38 .iter()
39 .filter_map(|p| p.address.as_ref().map(|addr| (addr, p)))
40 .collect();
41
42 let blocks = doc.text_blocks();
43 let mut parts: Vec<String> = Vec::new();
44 let mut idx = 0;
45 while let Some(block) = blocks.get(idx) {
46 if let Some(table_num) = top_table_number(block) {
47 let (table_text, next_idx) =
48 collect_table(blocks, idx + 1, table_num, &stories, format);
49 if !table_text.is_empty() {
50 parts.push(table_text);
51 }
52 idx = next_idx;
53 continue;
54 }
55 if let Some(rendered) = render_paragraph(block, &stories, format) {
56 parts.push(rendered);
57 }
58 idx += 1;
59 }
60
61 if parts.is_empty() {
62 String::new()
63 } else {
64 let mut out = parts.join("\n\n");
65 out.push('\n');
66 out
67 }
68}
69
70fn top_table_number(block: &TextBlock) -> Option<NonZeroUsize> {
71 if !matches!(block.kind, TextBlockKind::Table { .. }) {
72 return None;
73 }
74 match block.address.steps() {
75 [AddressStep::Table(num)] => Some(*num),
76 _ => None,
77 }
78}
79
80fn table_cell_coords(block: &TextBlock, table_num: NonZeroUsize) -> Option<(usize, usize)> {
81 match block.address.steps() {
82 [
83 AddressStep::Table(t),
84 AddressStep::Row(r),
85 AddressStep::Cell(c),
86 ..,
87 ] if *t == table_num => Some((r.get() - 1, c.get() - 1)),
88 _ => None,
89 }
90}
91
92fn collect_table(
93 blocks: &[TextBlock],
94 start: usize,
95 table_num: NonZeroUsize,
96 stories: &HashMap<&Address, &StoryParagraph>,
97 format: Format,
98) -> (String, usize) {
99 let mut grid: Vec<Vec<String>> = Vec::new();
100 let mut idx = start;
101 while let Some(block) = blocks.get(idx) {
102 let Some((row_idx, col_idx)) = table_cell_coords(block, table_num) else {
103 break;
104 };
105 if let Some(text) = paragraph_text(block, stories, format) {
106 append_cell(&mut grid, row_idx, col_idx, &text, format);
107 }
108 idx += 1;
109 }
110 let rendered = match format {
111 Format::PlainText => format_plain_table(&grid),
112 Format::Markdown => format_markdown_table(&grid),
113 };
114 (rendered, idx)
115}
116
117fn append_cell(
118 grid: &mut Vec<Vec<String>>,
119 row_idx: usize,
120 col_idx: usize,
121 text: &str,
122 format: Format,
123) {
124 if grid.len() <= row_idx {
125 grid.resize_with(row_idx + 1, Vec::new);
126 }
127 let Some(row) = grid.get_mut(row_idx) else {
128 return;
129 };
130 if row.len() <= col_idx {
131 row.resize_with(col_idx + 1, String::new);
132 }
133 let Some(cell) = row.get_mut(col_idx) else {
134 return;
135 };
136 if !cell.is_empty() {
137 cell.push_str(if format == Format::Markdown {
138 "<br>"
139 } else {
140 " "
141 });
142 }
143 cell.push_str(text);
144}
145
146fn format_plain_table(grid: &[Vec<String>]) -> String {
147 let mut lines: Vec<String> = Vec::with_capacity(grid.len());
148 for row in grid {
149 let joined = row
150 .iter()
151 .map(|c| c.replace('\n', " "))
152 .collect::<Vec<_>>()
153 .join("\t");
154 if !joined.trim().is_empty() {
155 lines.push(joined);
156 }
157 }
158 lines.join("\n")
159}
160
161fn format_markdown_table(grid: &[Vec<String>]) -> String {
162 let cols = grid.iter().map(Vec::len).max().unwrap_or(0);
163 if cols == 0 || grid.is_empty() {
164 return String::new();
165 }
166 let mut lines: Vec<String> = Vec::with_capacity(grid.len() + 1);
167 for (row_idx, row) in grid.iter().enumerate() {
168 lines.push(format_markdown_row(row, cols));
169 if row_idx == 0 {
170 let sep: Vec<&str> = vec!["---"; cols];
171 lines.push(format!("| {} |", sep.join(" | ")));
172 }
173 }
174 lines.join("\n")
175}
176
177fn format_markdown_row(row: &[String], cols: usize) -> String {
178 let mut cells: Vec<String> = Vec::with_capacity(cols);
179 for col_idx in 0..cols {
180 let raw = row.get(col_idx).map_or("", String::as_str);
181 cells.push(raw.replace('|', "\\|").replace('\n', "<br>"));
182 }
183 format!("| {} |", cells.join(" | "))
184}
185
186fn render_paragraph(
187 block: &TextBlock,
188 stories: &HashMap<&Address, &StoryParagraph>,
189 format: Format,
190) -> Option<String> {
191 let text = paragraph_text(block, stories, format)?;
192 if format == Format::Markdown
193 && let Some(level) = block.outline_level
194 {
195 let hashes = "#".repeat((usize::from(level) + 1).min(6));
196 let heading = text.replace('\n', " ");
197 return Some(format!("{hashes} {}", heading.trim()));
198 }
199 Some(text)
200}
201
202fn paragraph_text(
203 block: &TextBlock,
204 stories: &HashMap<&Address, &StoryParagraph>,
205 format: Format,
206) -> Option<String> {
207 let TextBlockKind::Paragraph { text: fallback, .. } = &block.kind else {
208 return None;
209 };
210 let story_text = stories.get(&block.address).and_then(|story| {
211 let rendered = if format == Format::Markdown {
212 render_markdown_links(&story.text, &story.links)
213 } else {
214 clean_story_text(&story.text)
215 };
216 (!rendered.trim().is_empty()).then_some(rendered)
217 });
218 let text = story_text.unwrap_or_else(|| fallback.clone());
219 if text.trim().is_empty() {
220 None
221 } else {
222 Some(text)
223 }
224}
225
226fn clean_story_text(raw: &str) -> String {
227 raw.replace(OBJECT_REPLACEMENT, "")
228}
229
230fn render_markdown_links(raw: &str, links: &[StoryLink]) -> String {
231 if links.is_empty() {
232 return clean_story_text(raw);
233 }
234 let mut out = String::with_capacity(raw.len());
235 let mut cursor = 0usize;
236 for link in links {
237 let LinkTarget::External(url) = &link.target else {
238 continue;
239 };
240 let start = link.start_byte as usize;
241 let end = link.end_byte as usize;
242 if start < cursor || end <= start || end > raw.len() {
243 continue;
244 }
245 let (Some(before), Some(label)) = (raw.get(cursor..start), raw.get(start..end)) else {
246 continue;
247 };
248 out.push_str(&clean_story_text(before));
249 let clean_label = clean_story_text(label);
250 if clean_label.trim().is_empty() {
251 out.push_str(&clean_label);
252 } else {
253 out.push('[');
254 out.push_str(&clean_label);
255 out.push_str("](");
256 out.push_str(url);
257 out.push(')');
258 }
259 cursor = end;
260 }
261 if let Some(tail) = raw.get(cursor..) {
262 out.push_str(&clean_story_text(tail));
263 }
264 out
265}
266
267#[cfg(test)]
268mod tests {
269 use std::io::Write as _;
270
271 use crate::{Document, FontDatabase, Options};
272
273 fn minimal_docx(body: &str) -> Vec<u8> {
274 let mut buf = std::io::Cursor::new(Vec::new());
275 {
276 let mut zip = zip::ZipWriter::new(&mut buf);
277 let opts = zip::write::SimpleFileOptions::default();
278 zip.start_file("[Content_Types].xml", opts).ok();
279 let _ = zip.write_all(
280 br#"<?xml version="1.0" encoding="UTF-8"?>
281<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
282 <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
283 <Default Extension="xml" ContentType="application/xml"/>
284 <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
285 <Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>
286</Types>"#,
287 );
288 zip.start_file("_rels/.rels", opts).ok();
289 let _ = zip.write_all(
290 br#"<?xml version="1.0" encoding="UTF-8"?>
291<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
292 <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
293</Relationships>"#,
294 );
295 zip.start_file("word/_rels/document.xml.rels", opts).ok();
296 let _ = zip.write_all(
297 br#"<?xml version="1.0" encoding="UTF-8"?>
298<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
299 <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
300 <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="https://f-office.org" TargetMode="External"/>
301</Relationships>"#,
302 );
303 zip.start_file("word/styles.xml", opts).ok();
304 let _ = zip.write_all(
305 br#"<?xml version="1.0" encoding="UTF-8"?>
306<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
307 <w:style w:type="paragraph" w:styleId="Heading1">
308 <w:name w:val="heading 1"/>
309 <w:pPr><w:outlineLvl w:val="0"/></w:pPr>
310 </w:style>
311</w:styles>"#,
312 );
313 zip.start_file("word/document.xml", opts).ok();
314 let xml = format!(
315 r#"<?xml version="1.0" encoding="UTF-8"?>
316<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
317 <w:body>{body}</w:body>
318</w:document>"#
319 );
320 let _ = zip.write_all(xml.as_bytes());
321 }
322 buf.into_inner()
323 }
324
325 #[test]
326 fn exports_headings_paragraphs_links_and_tables_to_plain_text_and_markdown()
327 -> Result<(), crate::Error> {
328 let body = concat!(
329 r#"<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Quarterly Report</w:t></w:r></w:p>"#,
330 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>"#,
331 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>"#,
332 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>"#
333 );
334 let bytes = minimal_docx(body);
335 let fonts = FontDatabase::new();
336 let doc = Document::open(&bytes, &fonts, &Options::default())?.value;
337
338 let plain = doc.to_plain_text();
339 assert_eq!(
340 plain,
341 "Quarterly Report\n\nVisit F-Office.\n\nMetric\tValue\nPages\t42\n"
342 );
343
344 let md = doc.to_markdown();
345 assert!(md.contains("# Quarterly Report\n\n"), "md={md:?}");
346 assert!(
347 md.contains("| Metric | Value |\n| --- | --- |\n| Pages | 42 |"),
348 "md={md:?}"
349 );
350 Ok(())
351 }
352}