text-document-io 1.11.1

Import/export for text-document: plain text, Markdown, HTML, LaTeX, DOCX
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
// Generated by Qleany v1.4.8 from feature_use_case.tera
use crate::ExportMarkdownDto;
use anyhow::{Result, anyhow};
use common::database::QueryUnitOfWork;
use common::database::rope_helpers::block_content_via_store;
use common::entities::{Block, Document, Frame, List, ListStyle, Root, Table, TableCell};
use common::format_runs::{InlineContent, InlineSegment};
use common::parser_tools::MarkdownExportOptions;
use common::types::{EntityId, ROOT_ENTITY_ID};
use std::collections::HashSet;

pub trait ExportMarkdownUnitOfWorkFactoryTrait: Send + Sync {
    fn create(&self) -> Box<dyn ExportMarkdownUnitOfWorkTrait>;
}

#[macros::uow_action(entity = "Root", action = "GetRO")]
#[macros::uow_action(entity = "Root", action = "GetRelationshipRO")]
#[macros::uow_action(entity = "Document", action = "GetRO")]
#[macros::uow_action(entity = "Document", action = "GetRelationshipRO")]
#[macros::uow_action(entity = "Frame", action = "GetRO")]
#[macros::uow_action(entity = "Frame", action = "GetMultiRO")]
#[macros::uow_action(entity = "Frame", action = "GetRelationshipRO")]
#[macros::uow_action(entity = "Block", action = "GetRO")]
#[macros::uow_action(entity = "Block", action = "GetMultiRO")]
#[macros::uow_action(entity = "Block", action = "GetRelationshipRO")]
#[macros::uow_action(entity = "List", action = "GetRO")]
#[macros::uow_action(entity = "Table", action = "GetRO")]
#[macros::uow_action(entity = "Table", action = "GetRelationshipRO")]
#[macros::uow_action(entity = "TableCell", action = "GetMultiRO")]
pub trait ExportMarkdownUnitOfWorkTrait: QueryUnitOfWork {}

pub struct ExportMarkdownUseCase {
    uow_factory: Box<dyn ExportMarkdownUnitOfWorkFactoryTrait>,
    options: MarkdownExportOptions,
    /// The document's resolved footnotes, set at the top of `execute` — a
    /// field, not a local, because `render_inline_segments` (the one place
    /// that needs to tell a nested-only citation from an ordinary one, see
    /// its own doc) sits several calls down a walk that threads only the uow
    /// and the block. Mirrors `ExportLatexUseCase::note_bodies`, which holds
    /// its own footnote state as a field for the identical reason.
    notes: crate::footnotes::Footnotes,
}

impl ExportMarkdownUseCase {
    pub fn new(
        uow_factory: Box<dyn ExportMarkdownUnitOfWorkFactoryTrait>,
        options: MarkdownExportOptions,
    ) -> Self {
        ExportMarkdownUseCase {
            uow_factory,
            options,
            notes: crate::footnotes::Footnotes::default(),
        }
    }

    pub fn execute(&mut self) -> Result<ExportMarkdownDto> {
        let uow = self.uow_factory.create();
        uow.begin_transaction()?;

        // Step 1: Get Root and Document
        let root = uow
            .get_root(&ROOT_ENTITY_ID)?
            .ok_or_else(|| anyhow!("Root entity not found"))?;

        let doc_ids = uow.get_root_relationship(
            &root.id,
            &common::direct_access::root::RootRelationshipField::Document,
        )?;
        let doc_id = *doc_ids
            .first()
            .ok_or_else(|| anyhow!("Root has no associated Document"))?;

        let frame_ids = uow.get_document_relationship(
            &doc_id,
            &common::direct_access::document::DocumentRelationshipField::Frames,
        )?;

        // Collect all cell frame IDs so we can skip them in the main loop
        let table_ids = uow.get_document_relationship(
            &doc_id,
            &common::direct_access::document::DocumentRelationshipField::Tables,
        )?;
        let mut cell_frame_ids: HashSet<EntityId> = HashSet::new();
        for tid in &table_ids {
            let cell_ids = uow.get_table_relationship(
                tid,
                &common::direct_access::table::TableRelationshipField::Cells,
            )?;
            let cells_opt = uow.get_table_cell_multi(&cell_ids)?;
            for cell in cells_opt.into_iter().flatten() {
                if let Some(cf_id) = cell.cell_frame {
                    cell_frame_ids.insert(cf_id);
                }
            }
        }

        let mut output_parts: Vec<String> = Vec::new();

        self.notes = crate::footnotes::Footnotes::build(&uow.store());

        for frame_id in &frame_ids {
            // Skip cell frames — they're rendered as part of their table
            if cell_frame_ids.contains(frame_id) {
                continue;
            }

            // Check if this is a table anchor frame
            // Skip note bodies: a definition is a top-level frame, so this
            // walk would otherwise render it as ordinary prose in the middle of
            // the chapter, at the point the definition happened to be typed.
            if self.notes.is_definition(*frame_id) {
                continue;
            }
            let frame = uow.get_frame(frame_id)?;
            // Only render top-level frames (parent_frame == None). Sub-frames
            // (e.g. blockquotes) are recursively rendered from their parent's
            // `render_frame_content` walk; rendering them at the top level
            // again would duplicate their content.
            if let Some(ref f) = frame
                && f.parent_frame.is_some()
            {
                continue;
            }
            if let Some(ref f) = frame
                && let Some(table_id) = f.table
            {
                let table_md = self.render_table_markdown(&*uow, &table_id)?;
                if !output_parts.is_empty() {
                    output_parts.push("\n\n".to_string());
                }
                output_parts.push(table_md);
                continue;
            }

            if let Some(ref f) = frame {
                let frame_text = self.render_frame_content(&*uow, f, &cell_frame_ids, "")?;
                if !frame_text.is_empty() {
                    if !output_parts.is_empty() {
                        output_parts.push("\n\n".to_string());
                    }
                    output_parts.push(frame_text);
                }
            }
        }

        // The definitions, after the prose. Markdown's footnote extension uses
        // djot's own shape, so this is the native construct rather than a
        // fallback: a reader that understands footnotes links them up, and one
        // that does not still shows the note as readable text at the end.
        //
        // Continuation lines are indented four spaces, which is what keeps a
        // multi-paragraph note attached to its definition instead of ending it.
        for (_, label, frame_id) in self.notes.in_print_order() {
            let frame = uow.get_frame(&frame_id)?;
            let Some(ref f) = frame else { continue };
            let body = self.render_frame_content(&*uow, f, &cell_frame_ids, "")?;
            if body.trim().is_empty() {
                continue;
            }
            if !output_parts.is_empty() {
                output_parts.push("\n\n".to_string());
            }
            let mut lines = body.trim().lines();
            let mut out = String::new();
            if let Some(first) = lines.next() {
                out.push_str(&format!("[^{label}]: {first}"));
            }
            for line in lines {
                out.push('\n');
                if !line.is_empty() {
                    out.push_str("    ");
                    out.push_str(line);
                }
            }
            output_parts.push(out);
        }

        uow.end_transaction()?;

        let markdown_text = output_parts.concat();

        Ok(ExportMarkdownDto { markdown_text })
    }

    /// Render the content of a frame by walking its `child_order`.
    /// Positive entries are block IDs, negative entries are negated
    /// sub-frame IDs. `quote_prefix` is prepended to every output line
    /// (e.g. "> " for blockquotes). Returns a single fully-joined
    /// String — inter-block / inter-frame separators are already baked
    /// in. Callers (both `execute` and this function's own recursion
    /// into sub-frames) must NOT add further "\n\n" around the result;
    /// doing so previously produced exponentially many extra blank
    /// lines for nested frames.
    fn render_frame_content(
        &self,
        uow: &dyn ExportMarkdownUnitOfWorkTrait,
        frame: &Frame,
        cell_frame_ids: &HashSet<EntityId>,
        quote_prefix: &str,
    ) -> Result<String> {
        let mut result = String::new();
        let mut prev_was_list = false;
        let mut ordered_list_counter: i64 = 0;
        let mut current_list_id: Option<EntityId> = None;

        // If child_order is empty, fall back to iterating blocks directly
        let use_child_order = !frame.child_order.is_empty();

        if use_child_order {
            for &entry in &frame.child_order {
                if entry > 0 {
                    // Positive: block ID
                    let block_id = entry as EntityId;
                    let block = uow.get_block(&block_id)?;
                    if let Some(ref b) = block {
                        let (line, is_list_item) = self.render_block_line(
                            uow,
                            b,
                            quote_prefix,
                            &mut ordered_list_counter,
                            &mut current_list_id,
                        )?;
                        if !result.is_empty() {
                            if is_list_item && prev_was_list {
                                result.push('\n');
                            } else {
                                result.push_str("\n\n");
                            }
                        }
                        result.push_str(&line);
                        prev_was_list = is_list_item;
                    }
                } else {
                    // Negative: negated sub-frame ID
                    let sub_frame_id = (-entry) as EntityId;
                    if cell_frame_ids.contains(&sub_frame_id) {
                        continue;
                    }
                    let sub_frame = uow.get_frame(&sub_frame_id)?;
                    if let Some(ref sf) = sub_frame {
                        // Check if sub-frame is a table anchor
                        if let Some(table_id) = sf.table {
                            let table_md = self.render_table_markdown(uow, &table_id)?;
                            let prefixed = if !quote_prefix.is_empty() {
                                prefix_lines(&table_md, quote_prefix)
                            } else {
                                table_md
                            };
                            if !result.is_empty() {
                                result.push_str("\n\n");
                            }
                            result.push_str(&prefixed);
                            prev_was_list = false;
                            current_list_id = None;
                            ordered_list_counter = 0;
                            continue;
                        }

                        // Blockquote sub-frame
                        let sub_prefix = if sf.fmt_is_blockquote == Some(true) {
                            format!("{}> ", quote_prefix)
                        } else {
                            quote_prefix.to_string()
                        };

                        let sub_text =
                            self.render_frame_content(uow, sf, cell_frame_ids, &sub_prefix)?;
                        if !sub_text.is_empty() {
                            if !result.is_empty() {
                                result.push_str("\n\n");
                            }
                            result.push_str(&sub_text);
                        }
                        prev_was_list = false;
                        current_list_id = None;
                        ordered_list_counter = 0;
                    }
                }
            }
        } else {
            // Fallback: iterate blocks from the Blocks relationship
            let block_ids = uow.get_frame_relationship(
                &frame.id,
                &common::direct_access::frame::FrameRelationshipField::Blocks,
            )?;

            if block_ids.is_empty() {
                return Ok(result);
            }

            let blocks_opt = uow.get_block_multi(&block_ids)?;
            let mut blocks: Vec<Block> = blocks_opt.into_iter().flatten().collect();
            blocks.sort_by_key(|b| b.document_position);

            for block in &blocks {
                let (line, is_list_item) = self.render_block_line(
                    uow,
                    block,
                    quote_prefix,
                    &mut ordered_list_counter,
                    &mut current_list_id,
                )?;
                if !result.is_empty() {
                    if is_list_item && prev_was_list {
                        result.push('\n');
                    } else {
                        result.push_str("\n\n");
                    }
                }
                result.push_str(&line);
                prev_was_list = is_list_item;
            }
        }

        Ok(result)
    }

    /// Render a single block into a markdown line string.
    /// Returns (rendered_line, is_list_item).
    fn render_block_line(
        &self,
        uow: &dyn ExportMarkdownUnitOfWorkTrait,
        block: &Block,
        quote_prefix: &str,
        ordered_list_counter: &mut i64,
        current_list_id: &mut Option<EntityId>,
    ) -> Result<(String, bool)> {
        // Check if this is a code block
        if block.fmt_is_code_block == Some(true) {
            let lang = block.fmt_code_language.as_deref().unwrap_or("");
            let block_text = block_content_via_store(block, &uow.store());
            let elements = common::format_runs_query::inline_segments_for_block(
                &uow.store(),
                block.id,
                &block_text,
            );

            // Concatenate raw text from elements, no formatting
            let mut raw_text = String::new();
            for elem in &elements {
                match &elem.content {
                    InlineContent::Text(t) => raw_text.push_str(t),
                    InlineContent::Empty => {}
                    // Neither has raw text to contribute to a verbatim block.
                    InlineContent::Image { .. } | InlineContent::FootnoteRef { .. } => {}
                }
            }

            let code_block = if quote_prefix.is_empty() {
                format!("```{}\n{}\n```", lang, raw_text)
            } else {
                let mut lines = Vec::new();
                lines.push(format!("{}```{}", quote_prefix, lang));
                for line in raw_text.lines() {
                    lines.push(format!("{}{}", quote_prefix, line));
                }
                // Handle the case where raw_text is empty or ends without newline
                if raw_text.is_empty() {
                    lines.push(quote_prefix.to_string());
                }
                lines.push(format!("{}```", quote_prefix));
                lines.join("\n")
            };

            *current_list_id = None;
            *ordered_list_counter = 0;
            return Ok((code_block, false));
        }

        // Synthesize inline segments view
        let block_text = block_content_via_store(block, &uow.store());
        let elements = common::format_runs_query::inline_segments_for_block(
            &uow.store(),
            block.id,
            &block_text,
        );

        // Check if block has a list
        let list_ids = uow.get_block_relationship(
            &block.id,
            &common::direct_access::block::BlockRelationshipField::List,
        )?;
        let list = if let Some(list_id) = list_ids.first() {
            uow.get_list(list_id)?
        } else {
            None
        };

        let is_list_item = list.is_some();

        // Build inline markdown text
        let inline_md = self.render_inline_segments(&elements)?;

        // Build the block line
        let block_line = if let Some(level) = block.fmt_heading_level {
            let prefix = "#".repeat(level as usize);
            format!("{}{} {}", quote_prefix, prefix, inline_md)
        } else if let Some(ref list_entity) = list {
            let indent_prefix = "  ".repeat(list_entity.indent as usize);
            match list_entity.style {
                ListStyle::Decimal
                | ListStyle::LowerAlpha
                | ListStyle::UpperAlpha
                | ListStyle::LowerRoman
                | ListStyle::UpperRoman => {
                    let this_list_id = list_ids.first().copied();
                    if this_list_id != *current_list_id {
                        *ordered_list_counter = 1;
                        *current_list_id = this_list_id;
                    } else {
                        *ordered_list_counter += 1;
                    }
                    format!(
                        "{}{}{}. {}",
                        quote_prefix, indent_prefix, ordered_list_counter, inline_md
                    )
                }
                _ => format!("{}{}- {}", quote_prefix, indent_prefix, inline_md),
            }
        } else {
            *current_list_id = None;
            *ordered_list_counter = 0;
            format!("{}{}", quote_prefix, inline_md)
        };

        // A page break is its own raw-HTML block above the line it precedes — Markdown
        // has nothing native to say this with, so the block is the least-bad carrier
        // (see `markdown_page_break`). Never on a list item: it would land inside the
        // list and break the run apart.
        let block_line = if self.options.page_breaks
            && block.fmt_page_break_before == Some(true)
            && !is_list_item
        {
            format!(
                "{quote_prefix}{}\n\n{block_line}",
                common::parser_tools::markdown_page_break()
            )
        } else {
            block_line
        };

        Ok((block_line, is_list_item))
    }

    /// Render inline segments into markdown text with formatting.
    fn render_inline_segments(&self, elements: &[InlineSegment]) -> Result<String> {
        let mut inline_md = String::new();
        for elem in elements {
            let is_code = elem.fmt_font_family.as_deref() == Some("monospace");
            let text = match &elem.content {
                // Markdown's own footnote-reference syntax, the same shape djot
                // uses. Emitted and done — it must not fall through into the
                // emphasis wrapping below.
                //
                // Unless the label is cited only from inside another note's own
                // body (`Footnotes::is_nested_reference` — see its doc, and
                // `footnotes.rs`'s module doc for why that citation is refused
                // rather than numbered): the notes loop below walks
                // `in_print_order()`, which never includes such a label, so its
                // `[^label]:` definition is never written. Emitting the
                // `[^label]` syntax anyway would leave a dangling reference in
                // the file — plain, escaped text instead, same as `Footnotes::
                // marker`'s own "visible and traceable" fallback. An ordinary
                // **dangling** reference (no definition anywhere) is not this:
                // it keeps the live `[^label]` syntax exactly as before, for
                // whatever host resolves it outside this document.
                InlineContent::FootnoteRef { label } => {
                    if self.notes.is_nested_reference(label) {
                        inline_md.push_str(&escape_markdown(label));
                    } else {
                        inline_md.push_str(&format!("[^{label}]"));
                    }
                    continue;
                }
                InlineContent::Text(t) => {
                    if is_code {
                        t.clone()
                    } else {
                        escape_markdown(t)
                    }
                }
                InlineContent::Image { name, alt, .. } => {
                    if self.options.omit_images {
                        // Not even the alt text: Markdown has no way to mark a
                        // deliberately absent image, so a bare description would
                        // read as a sentence the author never wrote.
                        String::new()
                    } else {
                        // Markdown has no attribute syntax, so display size cannot
                        // survive here; alt and source do.
                        format!("![{}]({})", alt, name)
                    }
                }
                InlineContent::Empty => String::new(),
            };

            if text.is_empty() {
                continue;
            }

            let mut formatted = text.clone();

            // Apply formatting (innermost first)
            if elem.fmt_font_family.as_deref() == Some("monospace") {
                formatted = format!("`{}`", formatted);
            }
            if elem.fmt_font_strikeout == Some(true) {
                formatted = format!("~~{}~~", formatted);
            }
            if elem.fmt_font_bold == Some(true) && elem.fmt_font_italic == Some(true) {
                formatted = format!("***{}***", formatted);
            } else if elem.fmt_font_bold == Some(true) {
                formatted = format!("**{}**", formatted);
            } else if elem.fmt_font_italic == Some(true) {
                formatted = format!("*{}*", formatted);
            }
            if let Some(ref href) = elem.fmt_anchor_href {
                formatted = format!("[{}]({})", formatted, href);
            }

            inline_md.push_str(&formatted);
        }
        Ok(inline_md)
    }

    fn render_table_markdown(
        &self,
        uow: &dyn ExportMarkdownUnitOfWorkTrait,
        table_id: &EntityId,
    ) -> Result<String> {
        let table = uow
            .get_table(table_id)?
            .ok_or_else(|| anyhow!("Table not found"))?;

        let cell_ids = uow.get_table_relationship(
            table_id,
            &common::direct_access::table::TableRelationshipField::Cells,
        )?;
        let cells_opt = uow.get_table_cell_multi(&cell_ids)?;
        let mut cells: Vec<TableCell> = cells_opt.into_iter().flatten().collect();
        cells.sort_by(|a, b| a.row.cmp(&b.row).then(a.column.cmp(&b.column)));

        let rows = table.rows as usize;
        let cols = table.columns as usize;

        // Build a grid of cell content strings
        let mut grid: Vec<Vec<String>> = vec![vec![String::new(); cols]; rows];

        for cell in &cells {
            let r = cell.row as usize;
            let c = cell.column as usize;
            if r >= rows || c >= cols {
                continue;
            }

            let mut cell_text = String::new();
            if let Some(cf_id) = cell.cell_frame {
                let block_ids = uow.get_frame_relationship(
                    &cf_id,
                    &common::direct_access::frame::FrameRelationshipField::Blocks,
                )?;
                let blocks_opt = uow.get_block_multi(&block_ids)?;
                let mut blocks: Vec<Block> = blocks_opt.into_iter().flatten().collect();
                blocks.sort_by_key(|b| b.document_position);

                let mut parts: Vec<String> = Vec::new();
                for block in &blocks {
                    let inline_md = self.render_inline_markdown(uow, block)?;
                    if !inline_md.is_empty() {
                        parts.push(inline_md);
                    }
                }
                cell_text = parts.join(" ");
            }

            grid[r][c] = cell_text;
        }

        // Render as pipe-delimited markdown table
        let mut md = String::new();

        for (r, row) in grid.iter().enumerate() {
            md.push('|');
            for cell_text in row {
                md.push(' ');
                md.push_str(cell_text);
                md.push_str(" |");
            }
            md.push('\n');

            // Add separator after header row
            if r == 0 {
                md.push('|');
                for _ in 0..cols {
                    md.push_str("---|");
                }
                md.push('\n');
            }
        }

        // Remove trailing newline
        if md.ends_with('\n') {
            md.pop();
        }

        Ok(md)
    }

    fn render_inline_markdown(
        &self,
        uow: &dyn ExportMarkdownUnitOfWorkTrait,
        block: &Block,
    ) -> Result<String> {
        let block_text = block_content_via_store(block, &uow.store());
        let elements = common::format_runs_query::inline_segments_for_block(
            &uow.store(),
            block.id,
            &block_text,
        );

        self.render_inline_segments(&elements)
    }
}

/// Prefix every line of `text` with `prefix`.
fn prefix_lines(text: &str, prefix: &str) -> String {
    text.lines()
        .map(|line| format!("{}{}", prefix, line))
        .collect::<Vec<_>>()
        .join("\n")
}

fn escape_markdown(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '\\' | '*' | '_' | '{' | '}' | '[' | ']' | '(' | ')' | '#' | '+' | '-' | '.' | '!'
            | '|' | '~' | '>' => {
                result.push('\\');
                result.push(c);
            }
            _ => result.push(c),
        }
    }
    result
}