text-document-io 1.12.0

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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
// Generated by Qleany v1.4.8 from feature_use_case.tera
use crate::ExportDjotDto;
use anyhow::{Result, anyhow};
use common::database::QueryUnitOfWork;
use common::database::rope_helpers::block_content_via_store;
use common::entities::{
    Alignment, Block, CharVerticalAlignment, Document, Frame, List, ListStyle, MarkerType, Root,
    SemanticRole, Table, TableCell, TextDirection,
};
use common::format_runs::{InlineContent, InlineSegment};
use common::parser_tools::DjotExportOptions;
// The single definition of both, shared with anything else converting plain text to Djot
// (a host app promoting a stored plain-text field, for one). Kept as aliases so this
// exporter's call sites read as they always did, while there is only one escaper to be
// wrong about the awkward strings.
use common::parser_tools::escape_djot_inline as escape_djot;
use common::parser_tools::guard_djot_block_start as guard_block_start;
use common::types::{EntityId, ROOT_ENTITY_ID};
use std::collections::HashSet;

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

#[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 ExportDjotUnitOfWorkTrait: QueryUnitOfWork {}

pub struct ExportDjotUseCase {
    uow_factory: Box<dyn ExportDjotUnitOfWorkFactoryTrait>,
    /// Copied off `options` at the top of `execute`. The inline renderer that
    /// needs it is reached both from `render_block_line` (which carries
    /// `options`) and from `render_inline_djot` (which does not), so a
    /// parameter would have to be threaded through a walk that otherwise has no
    /// interest in export settings. Mirrors `ExportMarkdownUseCase::options`.
    omit_images: bool,
}

impl ExportDjotUseCase {
    pub fn new(uow_factory: Box<dyn ExportDjotUnitOfWorkFactoryTrait>) -> Self {
        ExportDjotUseCase {
            uow_factory,
            omit_images: false,
        }
    }

    pub fn execute(&mut self, options: &DjotExportOptions) -> Result<ExportDjotDto> {
        self.omit_images = options.omit_images;
        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();

        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
            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_djot(&*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, "", options)?;
                if !frame_text.is_empty() {
                    if !output_parts.is_empty() {
                        output_parts.push("\n\n".to_string());
                    }
                    // A footnote definition frame is body content that has to
                    // announce whose body it is. Without the `[^label]:` prefix
                    // the note re-parses as an ordinary paragraph sitting where
                    // the definition was typed — the body survives, the fact
                    // that it *is* a note does not.
                    //
                    // Continuation lines are indented, which is how djot marks a
                    // multi-block note body as belonging to the definition
                    // rather than ending it.
                    if let Some(ref label) = f.footnote_label {
                        let mut lines = frame_text.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() {
                                continue;
                            }
                            out.push_str("    ");
                            out.push_str(line);
                        }
                        output_parts.push(out);
                    } else {
                        output_parts.push(frame_text);
                    }
                }
            }
        }

        uow.end_transaction()?;

        let djot_text = output_parts.concat();

        Ok(ExportDjotDto { djot_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 ExportDjotUnitOfWorkTrait,
        frame: &Frame,
        cell_frame_ids: &HashSet<EntityId>,
        quote_prefix: &str,
        options: &DjotExportOptions,
    ) -> Result<String> {
        let mut result = String::new();
        let mut ordered_list_counter: i64 = 0;
        let mut current_list_id: Option<EntityId> = None;
        // The frame's semantic role rides its first block and is then spent — a second
        // `{semantic_role=…}` further down would re-open the same claim on a paragraph
        // that is only a continuation of the quote.
        let mut first_block_role = frame.fmt_semantic_role.as_ref();

        // Every block/sub-frame is separated by a blank line. Djot renders the
        // resulting lists "loose", but the model does not distinguish
        // tight/loose, and the blank line is exactly what lets an indented
        // sub-list nest rather than fold into the parent item's paragraph.

        // 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, _) = self.render_block_line(
                            uow,
                            b,
                            quote_prefix,
                            first_block_role.take(),
                            &mut ordered_list_counter,
                            &mut current_list_id,
                            options,
                        )?;
                        if !result.is_empty() {
                            result.push_str("\n\n");
                        }
                        result.push_str(&line);
                    }
                } 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_djot(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);
                            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,
                            options,
                        )?;
                        if !sub_text.is_empty() {
                            if !result.is_empty() {
                                result.push_str("\n\n");
                            }
                            result.push_str(&sub_text);
                        }
                        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, _) = self.render_block_line(
                    uow,
                    block,
                    quote_prefix,
                    first_block_role.take(),
                    &mut ordered_list_counter,
                    &mut current_list_id,
                    options,
                )?;
                if !result.is_empty() {
                    result.push_str("\n\n");
                }
                result.push_str(&line);
            }
        }

        Ok(result)
    }

    /// Render a single block into a djot line string.
    /// Returns (rendered_line, is_list_item).
    #[allow(clippy::too_many_arguments)]
    fn render_block_line(
        &self,
        uow: &dyn ExportDjotUnitOfWorkTrait,
        block: &Block,
        quote_prefix: &str,
        frame_role: Option<&SemanticRole>,
        ordered_list_counter: &mut i64,
        current_list_id: &mut Option<EntityId>,
        options: &DjotExportOptions,
    ) -> 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 an image nor a footnote reference has raw text to
                    // contribute to a verbatim code 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 djot text
        let inline_md = self.render_inline_segments(&elements)?;

        // Build the block line. Standalone paragraphs and headings may carry a
        // leading `{key=value}` djot block-attribute line for the optional
        // block-style attributes; list items and code blocks do not.
        let attr_line = render_block_attrs(block, frame_role, options);
        let block_line = if let Some(level) = block.fmt_heading_level {
            let prefix = "#".repeat(level as usize);
            let head = format!("{}{} {}", quote_prefix, prefix, inline_md);
            prepend_block_attrs(&attr_line, quote_prefix, head)
        } else if let Some(ref list_entity) = list {
            let indent_prefix = "  ".repeat(list_entity.indent.max(0) as usize);
            let is_task = matches!(
                block.fmt_marker,
                Some(MarkerType::Checked) | Some(MarkerType::Unchecked)
            );
            if is_task {
                // Task list item: `<bullet> [ ]` / `<bullet> [x]`.
                let bullet = djot_bullet_char(&list_entity.style);
                let check = if block.fmt_marker == Some(MarkerType::Checked) {
                    "[x]"
                } else {
                    "[ ]"
                };
                format!("{quote_prefix}{indent_prefix}{bullet} {check} {inline_md}")
            } else {
                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;
                        }
                        let token = djot_ordered_token(&list_entity.style, *ordered_list_counter);
                        // Djot needs a delimiter after the number; default to
                        // `.` if none was recorded.
                        let suffix = if list_entity.suffix.is_empty() {
                            "."
                        } else {
                            list_entity.suffix.as_str()
                        };
                        format!(
                            "{quote_prefix}{indent_prefix}{}{token}{suffix} {inline_md}",
                            list_entity.prefix
                        )
                    }
                    _ => {
                        let bullet = djot_bullet_char(&list_entity.style);
                        format!("{quote_prefix}{indent_prefix}{bullet} {inline_md}")
                    }
                }
            }
        } else {
            *current_list_id = None;
            *ordered_list_counter = 0;
            // A paragraph's content sits at the start of a line; guard against
            // its leading characters being parsed as a block-construct marker.
            let para = format!("{}{}", quote_prefix, guard_block_start(&inline_md));
            prepend_block_attrs(&attr_line, quote_prefix, para)
        };

        Ok((block_line, is_list_item))
    }

    /// Render inline segments into djot text with formatting.
    ///
    /// Marks are applied innermost→outermost so the re-parse nests identically,
    /// producing a canonical form that makes export∘import a fixpoint:
    /// verbatim → **link** → subscript → superscript → delete → insert →
    /// strong/emphasis.
    ///
    /// # The link must be innermost
    ///
    /// It used to be outermost, which meant a **superscript link** was written
    /// `[^aa^](url)` — the `^` markers inside the brackets. `[^…]` is djot's
    /// **footnote-reference** syntax, so the re-parse read it as a footnote and
    /// the link was destroyed: `^[aa](url)^` exported to `[^aa^](url)`, which
    /// re-exported to `\(url\)`. Silent, total loss of the link text, in the
    /// format a manuscript is *saved* in.
    ///
    /// Wrapping the other way (`^[aa](url)^`) is equally valid djot for the same
    /// entity state, collides with nothing, and round-trips. The other marks
    /// (`*`, `_`, `{-`, `{+`) do not collide either way, so the one order that is
    /// safe for all of them is: link first, marks around it.
    fn render_inline_segments(&self, elements: &[InlineSegment]) -> Result<String> {
        let mut inline = String::new();
        for elem in elements {
            let is_code = elem.fmt_font_family.as_deref() == Some("monospace");

            // `(lead, body, trail)`: djot emphasis-family markers (`*`, `_`,
            // `^`, `~`, `{- -}`, `{+ +}`) must not sit directly against
            // whitespace, so for non-code text we move leading/trailing spaces
            // OUTSIDE all markers. Code is verbatim (jotdown keeps spaces), so
            // it is left intact.
            let (lead, mut formatted, trail): (&str, String, &str) = match &elem.content {
                InlineContent::Text(t) if is_code => ("", djot_inline_code(t), ""),
                InlineContent::Text(t) => {
                    let (l, core, tr) = split_surrounding_ws(t);
                    if core.is_empty() {
                        // Whitespace-only (or empty) run: emit verbatim, no
                        // markers (it carries no visible formatting).
                        inline.push_str(t);
                        continue;
                    }
                    (l, escape_djot(core), tr)
                }
                InlineContent::Image {
                    name,
                    alt,
                    width,
                    height,
                    ..
                } => {
                    if self.omit_images {
                        continue;
                    }
                    // Djot carries display size as inline attributes. Writing
                    // them keeps a resize durable across a save/reload, and
                    // round-trips through this crate's own importer.
                    let mut out = format!("![{}]({})", escape_djot(alt), name);
                    if *width > 0 && *height > 0 {
                        out.push_str(&format!("{{width={width} height={height}}}"));
                    }
                    ("", out, "")
                }
                // A footnote reference is written and **done** — it does not
                // fall through into the mark-wrapping cascade below the way an
                // image deliberately does (an image can be linked; a reference
                // cannot).
                //
                // Falling through would be the superscript-link bug wearing a
                // new hat. A reference normally carries
                // `vertical_alignment: SuperScript`, because that is what draws
                // the marker in the editor — so the cascade would wrap it as
                // `^[^label]^`, marking up syntax that every djot reader
                // already renders raised, and handing the re-parse a
                // superscript containing a footnote instead of a footnote.
                InlineContent::FootnoteRef { label } => {
                    inline.push_str(&format!("[^{label}]"));
                    continue;
                }
                InlineContent::Empty => continue,
            };

            // Innermost: the link. Putting it outside the marks writes `[^aa^](url)`,
            // and `[^…]` is a footnote reference — see the note above.
            if let Some(ref href) = elem.fmt_anchor_href {
                formatted = format!("[{formatted}]({})", djot_link_dest(href));
            }
            if elem.fmt_vertical_alignment == Some(CharVerticalAlignment::SubScript) {
                formatted = format!("~{formatted}~");
            } else if elem.fmt_vertical_alignment == Some(CharVerticalAlignment::SuperScript) {
                formatted = format!("^{formatted}^");
            }
            if elem.fmt_font_strikeout == Some(true) {
                formatted = format!("{{-{formatted}-}}");
            }
            if elem.fmt_font_underline == 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}_");
            }

            inline.push_str(lead);
            inline.push_str(&formatted);
            inline.push_str(trail);
        }
        Ok(inline)
    }

    fn render_table_djot(
        &self,
        uow: &dyn ExportDjotUnitOfWorkTrait,
        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_djot(uow, block)?;
                    if !inline_md.is_empty() {
                        parts.push(inline_md);
                    }
                }
                cell_text = parts.join(" ");
            }

            grid[r][c] = cell_text;
        }

        // Render as pipe-delimited djot 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_djot(
        &self,
        uow: &dyn ExportDjotUnitOfWorkTrait,
        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")
}

/// Render the optional block-style attributes of `block` as a djot
/// `{key=value …}` block-attribute string, honouring the export `options`.
/// Returns an empty string when the block carries none of the selected
/// attributes. Keys are the model field names so the importer reads them back
/// verbatim, making the model→djot→model round-trip a fixpoint.
fn render_block_attrs(
    block: &Block,
    frame_role: Option<&SemanticRole>,
    options: &DjotExportOptions,
) -> String {
    let mut pairs: Vec<String> = Vec::new();

    // The enclosing blockquote's role, written on its first block — djot block attributes
    // are the only channel, and the importer lifts it back onto the frame. Emitted first
    // so the pair reads as what it describes before the paragraph's own styling.
    if options.semantic_role
        && let Some(role) = frame_role
    {
        let v = match role {
            SemanticRole::Epigraph => "epigraph",
        };
        pairs.push(format!("semantic_role={v}"));
    }

    if options.alignment
        && let Some(alignment) = &block.fmt_alignment
    {
        let v = match alignment {
            Alignment::Left => "left",
            Alignment::Right => "right",
            Alignment::Center => "center",
            Alignment::Justify => "justify",
        };
        pairs.push(format!("alignment={v}"));
    }
    if options.line_height
        && let Some(lh) = block.fmt_line_height
    {
        pairs.push(format!("line_height={lh}"));
    }
    if options.direction
        && let Some(direction) = &block.fmt_direction
    {
        let v = match direction {
            TextDirection::LeftToRight => "ltr",
            TextDirection::RightToLeft => "rtl",
        };
        pairs.push(format!("direction={v}"));
    }
    if options.non_breakable_lines
        && let Some(nbl) = block.fmt_non_breakable_lines
    {
        pairs.push(format!("non_breakable_lines={nbl}"));
    }
    if options.page_break_before
        && let Some(pbb) = block.fmt_page_break_before
    {
        pairs.push(format!("page_break_before={pbb}"));
    }
    if options.background_color
        && let Some(bg) = &block.fmt_background_color
    {
        pairs.push(format!("background_color={}", djot_attr_value(bg)));
    }
    if options.top_margin
        && let Some(tm) = block.fmt_top_margin
    {
        pairs.push(format!("top_margin={tm}"));
    }
    if options.text_indent
        && let Some(ti) = block.fmt_text_indent
    {
        pairs.push(format!("text_indent={ti}"));
    }

    if pairs.is_empty() {
        String::new()
    } else {
        format!("{{{}}}", pairs.join(" "))
    }
}

/// Prepend a block-attribute line to a rendered block `body`, repeating the
/// blockquote `quote_prefix` on the attribute line. A no-op when `attr_line` is
/// empty.
fn prepend_block_attrs(attr_line: &str, quote_prefix: &str, body: String) -> String {
    if attr_line.is_empty() {
        body
    } else {
        format!("{quote_prefix}{attr_line}\n{body}")
    }
}

/// Encode an arbitrary attribute value as a double-quoted djot attribute value,
/// escaping `\` and `"` so it round-trips through jotdown's attribute parser
/// verbatim (covers colors like `#ff0000` and values containing spaces).
fn djot_attr_value(value: &str) -> String {
    let escaped = value.replace('\\', "\\\\").replace('"', "\\\"");
    format!("\"{escaped}\"")
}

/// Bullet character for an unordered/task list style (inverse of the importer's
/// `-`↔Disc / `*`↔Circle / `+`↔Square bijection).
fn djot_bullet_char(style: &ListStyle) -> &'static str {
    match style {
        ListStyle::Circle => "*",
        ListStyle::Square => "+",
        // Disc and any ordered style used as a task fallback.
        _ => "-",
    }
}

/// Render the counter token for an ordered list of the given style.
/// (Alpha is `a..z` cycling; Roman covers the common small range. Start number
/// is not modelled, so counting always begins at 1.)
fn djot_ordered_token(style: &ListStyle, n: i64) -> String {
    match style {
        ListStyle::LowerAlpha => djot_alpha(n, false),
        ListStyle::UpperAlpha => djot_alpha(n, true),
        ListStyle::LowerRoman => djot_roman(n).to_lowercase(),
        ListStyle::UpperRoman => djot_roman(n),
        // Decimal and any non-ordered fallback.
        _ => n.max(1).to_string(),
    }
}

fn djot_alpha(n: i64, upper: bool) -> String {
    let n = n.max(1);
    let base = if upper { b'A' } else { b'a' };
    // 1→a, 26→z, 27→aa, …
    let mut n = n as u64;
    let mut s = Vec::new();
    while n > 0 {
        let rem = ((n - 1) % 26) as u8;
        s.push(base + rem);
        n = (n - 1) / 26;
    }
    s.reverse();
    String::from_utf8(s).unwrap()
}

fn djot_roman(n: i64) -> String {
    let mut n = n.max(1);
    let table = [
        (1000, "M"),
        (900, "CM"),
        (500, "D"),
        (400, "CD"),
        (100, "C"),
        (90, "XC"),
        (50, "L"),
        (40, "XL"),
        (10, "X"),
        (9, "IX"),
        (5, "V"),
        (4, "IV"),
        (1, "I"),
    ];
    let mut out = String::new();
    for (value, sym) in table {
        while n >= value {
            out.push_str(sym);
            n -= value;
        }
    }
    out
}

/// Emit inline code as a backtick-fenced verbatim span, widening the fence past
/// any backtick run in the content and padding when it touches a backtick
/// (djot/CommonMark convention) so the content survives verbatim.
fn djot_inline_code(text: &str) -> String {
    let mut max_run = 0usize;
    let mut cur = 0usize;
    for c in text.chars() {
        if c == '`' {
            cur += 1;
            max_run = max_run.max(cur);
        } else {
            cur = 0;
        }
    }
    let fence = "`".repeat(max_run + 1);
    // jotdown verbatim is fully literal — it does NOT strip surrounding spaces
    // (verified against the reference) — so we must NOT pad: a pad space would
    // become part of the content and grow on every round trip. Sizing the fence
    // one wider than the longest interior backtick run is enough for all
    // import-reachable content (including content with leading/trailing spaces),
    // making `export∘import` a fixpoint.
    //
    // The sole exception is content that begins or ends with a backtick, which
    // would merge with the fence and produce invalid djot. We insert one space
    // there purely to keep the output valid. This case is not reachable by
    // importing djot (jotdown never emits verbatim whose content touches a
    // backtick), so it cannot occur on a real round trip.
    let lead = if text.starts_with('`') { " " } else { "" };
    let trail = if text.ends_with('`') { " " } else { "" };
    format!("{fence}{lead}{text}{trail}{fence}")
}

/// Split off leading/trailing ASCII space/tab runs: `(lead, core, trail)`.
/// `core` is empty when the input is entirely whitespace.
fn split_surrounding_ws(s: &str) -> (&str, &str, &str) {
    let is_ws = |c: char| c == ' ' || c == '\t';
    let start = s.len() - s.trim_start_matches(is_ws).len();
    let end = s.trim_end_matches(is_ws).len();
    if end <= start {
        (s, "", "")
    } else {
        (&s[..start], &s[start..end], &s[end..])
    }
}

/// Render a link destination. Wrap in angle brackets when it contains a
/// character that would otherwise terminate or corrupt the `(...)` dest.
fn djot_link_dest(href: &str) -> String {
    if href.contains([')', '(', ' ', '<', '>']) {
        format!("<{}>", href.replace('>', "%3E").replace('<', "%3C"))
    } else {
        href.to_string()
    }
}