text-document-io 1.8.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
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
// Generated by Qleany v1.4.8 from feature_use_case.tera
use crate::ExportDocxDto;
use crate::ExportDocxResultDto;
use anyhow::{Result, anyhow};
use common::database::QueryUnitOfWork;
use common::database::rope_helpers::block_content_via_store;
use common::entities::{
    Alignment, Block, Document, Frame, List, ListStyle, MarkerType, Root, Table, TableCell,
};
use common::format_runs::{InlineContent, InlineSegment};
use common::long_operation::LongOperation;
use common::types::{EntityId, ROOT_ENTITY_ID};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

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

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

pub struct ExportDocxUseCase {
    uow_factory: Box<dyn ExportDocxUnitOfWorkFactoryTrait>,
    dto: ExportDocxDto,
}

impl ExportDocxUseCase {
    pub fn new(
        uow_factory: Box<dyn ExportDocxUnitOfWorkFactoryTrait>,
        dto: &ExportDocxDto,
    ) -> Self {
        ExportDocxUseCase {
            uow_factory,
            dto: dto.clone(),
        }
    }
}

impl LongOperation for ExportDocxUseCase {
    type Output = ExportDocxResultDto;

    fn execute(
        &self,
        progress_callback: Box<dyn Fn(common::long_operation::OperationProgress) + Send>,
        cancel_flag: Arc<AtomicBool>,
    ) -> Result<Self::Output> {
        // Validate output path
        let output_path = std::path::Path::new(&self.dto.output_path);
        if let Some(parent) = output_path.parent()
            && !parent.as_os_str().is_empty()
            && !parent.exists()
        {
            return Err(anyhow!(
                "Output directory does not exist: '{}'",
                parent.display()
            ));
        }

        progress_callback(common::long_operation::OperationProgress::new(
            0.0,
            Some("Starting DOCX export...".to_string()),
        ));

        let uow = self.uow_factory.create();
        uow.begin_transaction()?;

        let build_result = self.build_docx(
            &*uow,
            progress_callback.as_ref(),
            Some(cancel_flag.as_ref()),
        );

        uow.end_transaction()?;

        let (docx, paragraph_count) = build_result?;

        progress_callback(common::long_operation::OperationProgress::new(
            90.0,
            Some("Writing DOCX file...".to_string()),
        ));

        // Write to file
        let file = std::fs::File::create(&self.dto.output_path).map_err(|e| {
            anyhow!(
                "Failed to create output file '{}': {}",
                self.dto.output_path,
                e
            )
        })?;
        docx.build()
            .pack(file)
            .map_err(|e| anyhow!("Failed to write DOCX: {}", e))?;

        progress_callback(common::long_operation::OperationProgress::new(
            100.0,
            Some("completed".to_string()),
        ));

        Ok(ExportDocxResultDto {
            file_path: self.dto.output_path.clone(),
            paragraph_count,
        })
    }
}

/// One unit-step of left indentation, in twips (1/20 pt). 720 twips = 0.5",
/// the conventional Word indent step used for both blockquote nesting and list
/// indentation.
const INDENT_STEP_TWIPS: i32 = 720;

/// Hanging indent applied to numbered/bulleted/task paragraphs so the marker
/// sits in the gutter and the text aligns, in twips.
const HANGING_TWIPS: i32 = 360;

/// Light-grey fill behind code blocks, as an `RRGGBB` hex string.
const CODE_BLOCK_FILL: &str = "F5F5F5";

/// A rendered top-level document child. The DOCX builder consumes `self` and
/// returns a new value on every `add_*`, so we cannot thread a `&mut Docx`
/// through the recursive frame walk; instead each block/table is rendered into
/// one of these and applied to the document in a final pass.
enum DocxElement {
    Paragraph(Box<docx_rs::Paragraph>),
    Table(Box<docx_rs::Table>),
}

/// Accumulates the numbering definitions referenced by list paragraphs.
///
/// Each `List` entity maps to its own numbering instance so that ordered
/// counters restart per list (two separate ordered lists each begin at 1).
/// Definitions are registered on the `Docx` after the whole tree is walked.
#[derive(Default)]
struct NumberingBuilder {
    /// `List` entity id -> assigned numbering id.
    map: HashMap<EntityId, usize>,
    defs: Vec<(docx_rs::AbstractNumbering, docx_rs::Numbering)>,
}

impl NumberingBuilder {
    /// Return the numbering id for `list`, creating its abstract-numbering and
    /// numbering definitions on first use.
    fn get_or_create(&mut self, list_id: EntityId, list: &List) -> usize {
        if let Some(&id) = self.map.get(&list_id) {
            return id;
        }
        // Numbering ids are 1-based; `map.len()` is the count assigned so far.
        let id = self.map.len() + 1;
        let abstract_num = build_abstract_numbering(id, list);
        let numbering = docx_rs::Numbering::new(id, id);
        self.defs.push((abstract_num, numbering));
        self.map.insert(list_id, id);
        id
    }
}

impl ExportDocxUseCase {
    /// Assemble the in-memory DOCX document from the store, performing no file
    /// I/O. Returns the document together with the number of top-level elements
    /// (paragraphs and tables) emitted, which is reported as `paragraph_count`.
    ///
    /// `execute` uses it and then packs the result to disk; the controller
    /// exposes a file-less variant for tests via [`Self::build_document`].
    pub(crate) fn build_docx(
        &self,
        uow: &dyn ExportDocxUnitOfWorkTrait,
        progress_callback: &dyn Fn(common::long_operation::OperationProgress),
        cancel_flag: Option<&AtomicBool>,
    ) -> Result<(docx_rs::Docx, i64)> {
        use docx_rs::*;

        // 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 walk; they
        // are rendered as part of their owning table.
        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);
                }
            }
        }

        progress_callback(common::long_operation::OperationProgress::new(
            10.0,
            Some("Walking document tree...".to_string()),
        ));

        let mut numbering = NumberingBuilder::default();
        let mut elements: Vec<DocxElement> = Vec::new();

        let total_frames = frame_ids.len().max(1);
        for (frame_idx, frame_id) in frame_ids.iter().enumerate() {
            check_cancelled(cancel_flag)?;

            // Skip cell frames — rendered as part of their table.
            if cell_frame_ids.contains(frame_id) {
                continue;
            }

            let frame = uow.get_frame(frame_id)?;
            let Some(frame) = frame else {
                continue;
            };

            // Only top-level frames are walked here. Sub-frames (blockquotes,
            // nested content) are reached recursively from their parent's
            // `child_order`; rendering them again at the top level would
            // duplicate their content.
            if frame.parent_frame.is_some() {
                continue;
            }

            // A table anchor frame contributes one table.
            if let Some(table_id) = frame.table {
                let table = self.render_table_docx(uow, &table_id, &mut numbering)?;
                elements.push(DocxElement::Table(Box::new(table)));
                continue;
            }

            self.render_frame_content(
                uow,
                &frame,
                &cell_frame_ids,
                0,
                &mut numbering,
                cancel_flag,
                &mut elements,
            )?;

            let pct = 10.0 + (frame_idx as f32 / total_frames as f32) * 70.0;
            progress_callback(common::long_operation::OperationProgress::new(
                pct,
                Some(format!(
                    "Processing frame {}/{}",
                    frame_idx + 1,
                    total_frames
                )),
            ));
        }

        progress_callback(common::long_operation::OperationProgress::new(
            85.0,
            Some("Assembling document...".to_string()),
        ));

        let paragraph_count = elements.len() as i64;

        let mut docx = Docx::new();
        // Register numbering definitions before the body so the referenced ids
        // resolve.
        for (abstract_num, num) in numbering.defs {
            docx = docx.add_abstract_numbering(abstract_num).add_numbering(num);
        }
        for element in elements {
            docx = match element {
                DocxElement::Paragraph(p) => docx.add_paragraph(*p),
                DocxElement::Table(t) => docx.add_table(*t),
            };
        }

        // Page geometry + base typography + running header, from the caller's options.
        docx = self.apply_document_options(docx);

        Ok((docx, paragraph_count))
    }

    /// Apply the document-wide export options (page size, margins, default font/size, and an
    /// optional page-number running header) onto the assembled `Docx`. A default
    /// [`common::parser_tools::DocxExportOptions`] leaves the docx-rs built-in defaults untouched.
    fn apply_document_options(&self, mut docx: docx_rs::Docx) -> docx_rs::Docx {
        use docx_rs::*;
        let o = &self.dto.options;

        if let (Some(w), Some(h)) = (o.page_width_twips, o.page_height_twips) {
            docx = docx.page_size(w, h);
        }
        if o.margin_top_twips.is_some()
            || o.margin_bottom_twips.is_some()
            || o.margin_left_twips.is_some()
            || o.margin_right_twips.is_some()
        {
            // docx-rs's PageMargin defaults each edge to 1440 twips (1"), so an unset edge
            // keeps that conventional default rather than collapsing to zero.
            let mut m = PageMargin::new();
            m = m.top(o.margin_top_twips.unwrap_or(1440));
            m = m.bottom(o.margin_bottom_twips.unwrap_or(1440));
            m = m.left(o.margin_left_twips.unwrap_or(1440));
            m = m.right(o.margin_right_twips.unwrap_or(1440));
            docx = docx.page_margin(m);
        }
        if let Some(family) = &o.font_family {
            docx = docx.default_fonts(
                RunFonts::new()
                    .ascii(family)
                    .hi_ansi(family)
                    .cs(family)
                    .east_asia(family),
            );
        }
        if let Some(half_pt) = o.font_half_points {
            docx = docx.default_size(half_pt);
        }
        if o.page_numbers {
            let mut header_para = Paragraph::new().align(AlignmentType::Right);
            if let Some(text) = &o.running_header
                && !text.trim().is_empty()
            {
                header_para =
                    header_para.add_run(Run::new().add_text(format!("{}   ", text.trim())));
            }
            header_para = header_para.add_page_num(PageNum::new());
            docx = docx.header(Header::new().add_paragraph(header_para));
        }
        docx
    }

    /// Build the document without any file I/O, using a no-op progress callback
    /// and no cancellation. Intended for callers (notably tests) that want to
    /// inspect the produced structure directly.
    pub(crate) fn build_document(&self) -> Result<(docx_rs::Docx, i64)> {
        let uow = self.uow_factory.create();
        uow.begin_transaction()?;
        let result = self.build_docx(&*uow, &|_progress| {}, None);
        uow.end_transaction()?;
        result
    }

    /// Walk a frame's `child_order`, appending rendered paragraphs/tables to
    /// `out`. `quote_depth` is the current blockquote nesting level (0 at the
    /// document body), used to compute left indentation.
    #[allow(clippy::too_many_arguments)]
    fn render_frame_content(
        &self,
        uow: &dyn ExportDocxUnitOfWorkTrait,
        frame: &Frame,
        cell_frame_ids: &HashSet<EntityId>,
        quote_depth: usize,
        numbering: &mut NumberingBuilder,
        cancel_flag: Option<&AtomicBool>,
        out: &mut Vec<DocxElement>,
    ) -> Result<()> {
        if !frame.child_order.is_empty() {
            for &entry in &frame.child_order {
                check_cancelled(cancel_flag)?;
                // `child_order` encodes block ids as positive and sub-frame ids
                // as negated. Entity ids are 1-based, so a 0 entry is malformed;
                // skip it rather than dispatching it as the sub-frame `-0`.
                if entry == 0 {
                    continue;
                }
                if entry > 0 {
                    // Positive: a block id.
                    let block_id = entry as EntityId;
                    if let Some(block) = uow.get_block(&block_id)? {
                        let paragraph = self.render_block(uow, &block, quote_depth, numbering)?;
                        out.push(DocxElement::Paragraph(Box::new(paragraph)));
                    }
                } else {
                    // Negative: a negated sub-frame id.
                    let sub_frame_id = (-entry) as EntityId;
                    if cell_frame_ids.contains(&sub_frame_id) {
                        continue;
                    }
                    if let Some(sub_frame) = uow.get_frame(&sub_frame_id)? {
                        // Table anchor sub-frame.
                        if let Some(table_id) = sub_frame.table {
                            let table = self.render_table_docx(uow, &table_id, numbering)?;
                            out.push(DocxElement::Table(Box::new(table)));
                            continue;
                        }
                        // A blockquote sub-frame deepens the indent; any other
                        // sub-frame is rendered inline at the same depth.
                        let sub_depth = if sub_frame.fmt_is_blockquote == Some(true) {
                            quote_depth + 1
                        } else {
                            quote_depth
                        };
                        self.render_frame_content(
                            uow,
                            &sub_frame,
                            cell_frame_ids,
                            sub_depth,
                            numbering,
                            cancel_flag,
                            out,
                        )?;
                    }
                }
            }
        } else {
            // Fallback: no child_order recorded — iterate the Blocks
            // relationship in document order.
            let block_ids = uow.get_frame_relationship(
                &frame.id,
                &common::direct_access::frame::FrameRelationshipField::Blocks,
            )?;
            if block_ids.is_empty() {
                return Ok(());
            }
            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 {
                check_cancelled(cancel_flag)?;
                let paragraph = self.render_block(uow, block, quote_depth, numbering)?;
                out.push(DocxElement::Paragraph(Box::new(paragraph)));
            }
        }
        Ok(())
    }

    /// Render a single block into one DOCX paragraph.
    ///
    /// Dispatch priority mirrors the djot exporter: code block, then heading,
    /// then list item, then plain paragraph.
    fn render_block(
        &self,
        uow: &dyn ExportDocxUnitOfWorkTrait,
        block: &Block,
        quote_depth: usize,
        numbering: &mut NumberingBuilder,
    ) -> Result<docx_rs::Paragraph> {
        use docx_rs::*;

        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,
        );

        let quote_indent = quote_depth as i32 * INDENT_STEP_TWIPS;

        // --- Code block ------------------------------------------------------
        if block.fmt_is_code_block == Some(true) {
            return Ok(render_code_block(&elements, quote_indent));
        }

        // --- Resolve list membership ----------------------------------------
        let list_ids = uow.get_block_relationship(
            &block.id,
            &common::direct_access::block::BlockRelationshipField::List,
        )?;
        let list = match list_ids.first() {
            Some(list_id) => uow.get_list(list_id)?.map(|l| (*list_id, l)),
            None => None,
        };

        let mut paragraph = Paragraph::new();

        // Common paragraph-level formatting. Heading style is applied in the
        // dispatch below so it does not interfere with list/code handling.
        if let Some(lh) = block.fmt_line_height {
            // thousandths → 240ths: 1000 = single (240), 1500 = 1.5 (360).
            let twips = (lh as f64 / 1000.0 * 240.0) as i32;
            paragraph = paragraph.line_spacing(
                LineSpacing::new()
                    .line_rule(LineSpacingType::Auto)
                    .line(twips),
            );
        }
        if block.fmt_non_breakable_lines == Some(true) {
            paragraph = paragraph.keep_lines(true);
        }
        if let Some(alignment) = &block.fmt_alignment {
            paragraph = paragraph.align(map_alignment(alignment));
        }
        // Per-block RTL → a paragraph-level `<w:bidi/>`. This is the only bidi primitive
        // docx-rs exposes (no run-level `rtl`, no section-level `<w:bidi/>`), but it correctly
        // right-orders a right-to-left paragraph — and it is applied to every paragraph
        // (headings included), independent of the manuscript options, so a document that only
        // mixes in a few RTL scenes still exports them correctly through plain `to_docx`.
        if block.fmt_direction == Some(common::entities::TextDirection::RightToLeft) {
            paragraph.property = paragraph.property.bidi(true);
        }

        let is_task = matches!(
            block.fmt_marker,
            Some(MarkerType::Checked) | Some(MarkerType::Unchecked)
        );

        if let Some(level) = block.fmt_heading_level {
            // Heading takes priority over list membership (mirrors djot).
            let style_name = format!("Heading{}", level.clamp(1, 6));
            paragraph = paragraph.style(&style_name);
            if quote_indent > 0 {
                paragraph = paragraph.indent(Some(quote_indent), None, None, None);
            }
        } else if let Some((list_id, list_entity)) = &list {
            let level = list_entity.indent.clamp(0, 8) as usize;
            if is_task {
                // Task items carry a checkbox glyph instead of an auto-number;
                // they are indented like a list item.
                let left = quote_indent + INDENT_STEP_TWIPS * (level as i32 + 1);
                paragraph = paragraph.indent(
                    Some(left),
                    Some(SpecialIndentType::Hanging(HANGING_TWIPS)),
                    None,
                    None,
                );
                let glyph = if block.fmt_marker == Some(MarkerType::Checked) {
                    "\u{2612} " //                } else {
                    "\u{2610} " //                };
                paragraph = paragraph.add_run(Run::new().add_text(glyph));
            } else {
                let num_id = numbering.get_or_create(*list_id, list_entity);
                paragraph = paragraph.numbering(NumberingId::new(num_id), IndentLevel::new(level));
                // A blockquoted list needs an explicit left indent on top of
                // the numbering geometry; an un-quoted list relies on the
                // numbering definition's own indent.
                if quote_indent > 0 {
                    let left = quote_indent + INDENT_STEP_TWIPS * (level as i32 + 1);
                    paragraph = paragraph.indent(
                        Some(left),
                        Some(SpecialIndentType::Hanging(HANGING_TWIPS)),
                        None,
                        None,
                    );
                }
            }
        } else {
            // Plain body paragraph: manuscript typography (line spacing, first-line indent,
            // paragraph spacing, alignment) from the export options, over any blockquote indent.
            paragraph = self.apply_body_style(paragraph, block, quote_indent);
        }

        Ok(add_inline_content(paragraph, &elements))
    }

    /// Apply the manuscript body-paragraph options to a plain paragraph. Each piece is applied
    /// only when the corresponding option is set (and the block didn't already carry its own),
    /// so a default [`common::parser_tools::DocxExportOptions`] leaves the paragraph exactly as plain `to_docx`
    /// produced it — including keeping any blockquote left indent.
    fn apply_body_style(
        &self,
        mut p: docx_rs::Paragraph,
        block: &Block,
        quote_indent: i32,
    ) -> docx_rs::Paragraph {
        use docx_rs::*;
        let o = &self.dto.options;
        let rtl = block.fmt_direction == Some(common::entities::TextDirection::RightToLeft);

        // Combined line spacing: line height (unless the block set its own) + space-after.
        let mut ls = LineSpacing::new();
        let mut ls_used = false;
        if block.fmt_line_height.is_none()
            && let Some(line) = o.line_spacing_twips
        {
            ls = ls.line_rule(LineSpacingType::Auto).line(line);
            ls_used = true;
        }
        if let Some(after) = o.paragraph_spacing_after_twips.filter(|&a| a > 0) {
            ls = ls.after(after as u32);
            ls_used = true;
        }
        if ls_used {
            p = p.line_spacing(ls);
        }

        // Indent: any blockquote left indent + an optional first-line indent.
        let first_line = o.first_line_indent_twips.filter(|&f| f > 0);
        let left = (quote_indent > 0).then_some(quote_indent);
        if left.is_some() || first_line.is_some() {
            p = p.indent(
                left,
                first_line.map(SpecialIndentType::FirstLine),
                None,
                None,
            );
        }

        // Alignment (only when the block didn't carry its own, and only when the options ask
        // for it — a plain LTR export leaves the docx default so existing behaviour is intact).
        if block.fmt_alignment.is_none() {
            let align = if o.justify {
                Some(AlignmentType::Justified)
            } else if rtl {
                Some(AlignmentType::Right)
            } else {
                None
            };
            if let Some(a) = align {
                p = p.align(a);
            }
        }
        p
    }

    fn render_table_docx(
        &self,
        uow: &dyn ExportDocxUnitOfWorkTrait,
        table_id: &EntityId,
        numbering: &mut NumberingBuilder,
    ) -> Result<docx_rs::Table> {
        use docx_rs::*;

        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<common::entities::TableCell> = cells_opt.into_iter().flatten().collect();
        cells.sort_by(|a, b| a.row.cmp(&b.row).then(a.column.cmp(&b.column)));

        // Build a grid to track which cells are covered by spans.
        let rows = table.rows as usize;
        let cols = table.columns as usize;
        let mut covered = vec![vec![false; cols]; rows];

        // Build column grid widths.
        let grid: Vec<usize> = table.column_widths.iter().map(|w| *w as usize).collect();

        let mut docx_rows: Vec<TableRow> = Vec::new();

        for r in 0..rows {
            let mut docx_cells: Vec<docx_rs::TableCell> = Vec::new();

            for c in 0..cols {
                if covered[r][c] {
                    // Position covered by a row/column span from another cell.
                    // A vertically merged continuation still needs a <w:tc>
                    // with vMerge continue; a column span simply omits the cell.
                    let needs_vmerge_continue = r > 0 && {
                        cells.iter().any(|cell| {
                            cell.column == c as i64
                                && cell.row < r as i64
                                && (cell.row + cell.row_span) > r as i64
                        })
                    };
                    if needs_vmerge_continue {
                        let cont_cell =
                            docx_rs::TableCell::new().vertical_merge(VMergeType::Continue);
                        docx_cells.push(cont_cell);
                    }
                    continue;
                }

                let cell = cells
                    .iter()
                    .find(|cell| cell.row == r as i64 && cell.column == c as i64);

                if let Some(cell) = cell {
                    let mut docx_cell = docx_rs::TableCell::new();

                    // Spans are `i64`; clamp to >= 1 before any `as usize` so a
                    // malformed (0 or negative) span can never wrap to a huge
                    // `usize` and blow up the coverage loop or the grid span.
                    let row_span = cell.row_span.max(1) as usize;
                    let col_span = cell.column_span.max(1) as usize;

                    if col_span > 1 {
                        docx_cell = docx_cell.grid_span(col_span);
                    }
                    if row_span > 1 {
                        docx_cell = docx_cell.vertical_merge(VMergeType::Restart);
                    }

                    // Render the cell's frame as a sequence of paragraphs/tables.
                    if let Some(cf_id) = cell.cell_frame
                        && let Some(cell_frame) = uow.get_frame(&cf_id)?
                    {
                        let mut cell_elements: Vec<DocxElement> = Vec::new();
                        // The document-level cell-frame skip set does not apply
                        // inside a cell, so pass an empty set here.
                        self.render_frame_content(
                            uow,
                            &cell_frame,
                            &HashSet::new(),
                            0,
                            numbering,
                            None,
                            &mut cell_elements,
                        )?;
                        for element in cell_elements {
                            docx_cell = match element {
                                DocxElement::Paragraph(p) => docx_cell.add_paragraph(*p),
                                DocxElement::Table(t) => docx_cell.add_table(*t),
                            };
                        }
                    }

                    docx_cells.push(docx_cell);

                    // Mark spanned cells as covered.
                    for sr in 0..row_span {
                        for sc in 0..col_span {
                            if sr == 0 && sc == 0 {
                                continue;
                            }
                            if r + sr < rows && c + sc < cols {
                                covered[r + sr][c + sc] = true;
                            }
                        }
                    }
                } else {
                    // Empty cell — no TableCell entity at this position.
                    let docx_cell = docx_rs::TableCell::new().add_paragraph(Paragraph::new());
                    docx_cells.push(docx_cell);
                }
            }

            docx_rows.push(TableRow::new(docx_cells));
        }

        let mut docx_table = docx_rs::Table::new(docx_rows);
        if !grid.is_empty() {
            docx_table = docx_table.set_grid(grid);
        }

        Ok(docx_table)
    }
}

/// Return `Err` if a cancellation flag is present and set.
fn check_cancelled(cancel_flag: Option<&AtomicBool>) -> Result<()> {
    if let Some(flag) = cancel_flag
        && flag.load(Ordering::Relaxed)
    {
        return Err(anyhow!("Operation was cancelled"));
    }
    Ok(())
}

/// Map the model's paragraph alignment to docx-rs.
fn map_alignment(alignment: &Alignment) -> docx_rs::AlignmentType {
    use docx_rs::AlignmentType;
    match alignment {
        Alignment::Left => AlignmentType::Left,
        Alignment::Right => AlignmentType::Right,
        Alignment::Center => AlignmentType::Center,
        Alignment::Justify => AlignmentType::Justified,
    }
}

/// Render a fenced/code block as a single monospaced, shaded paragraph.
///
/// Inline formatting is dropped (only the raw text matters, mirroring djot).
/// Embedded newlines become soft line breaks so a multi-line block stays one
/// paragraph.
fn render_code_block(elements: &[InlineSegment], quote_indent: i32) -> docx_rs::Paragraph {
    use docx_rs::*;

    let mut raw = String::new();
    for elem in elements {
        if let InlineContent::Text(t) = &elem.content {
            raw.push_str(t);
        }
    }

    let mut paragraph = Paragraph::new().keep_lines(true);
    if quote_indent > 0 {
        paragraph = paragraph.indent(Some(quote_indent), None, None, None);
    }

    for (idx, line) in raw.split('\n').enumerate() {
        let mut run = Run::new()
            .fonts(RunFonts::new().ascii("Courier New").hi_ansi("Courier New"))
            .shading(
                Shading::new()
                    .shd_type(ShdType::Clear)
                    .fill(CODE_BLOCK_FILL),
            );
        if idx > 0 {
            run = run.add_break(BreakType::TextWrapping);
        }
        if !line.is_empty() {
            run = run.add_text(line);
        }
        paragraph = paragraph.add_run(run);
    }

    paragraph
}

/// Build a DOCX run for one inline segment, applying its character formatting.
/// Returns `None` for segments that contribute no text.
fn build_run(elem: &InlineSegment) -> Option<docx_rs::Run> {
    use docx_rs::*;

    let text = match &elem.content {
        InlineContent::Text(t) => t.clone(),
        InlineContent::Image { name, .. } => format!("[Image: {}]", name),
        InlineContent::Empty => return None,
    };
    if text.is_empty() {
        return None;
    }

    let mut run = Run::new().add_text(text);
    if elem.fmt_font_bold == Some(true) {
        run = run.bold();
    }
    if elem.fmt_font_italic == Some(true) {
        run = run.italic();
    }
    if elem.fmt_font_underline == Some(true) {
        run = run.underline("single");
    }
    if elem.fmt_font_strikeout == Some(true) {
        run = run.strike();
    }
    if elem.fmt_font_family.as_deref() == Some("monospace") {
        run = run.fonts(RunFonts::new().ascii("Courier New").hi_ansi("Courier New"));
    }
    Some(run)
}

/// Append the inline content of a block to `paragraph`, wrapping runs that
/// share a hyperlink `href` in a single `<w:hyperlink>`.
fn add_inline_content(
    mut paragraph: docx_rs::Paragraph,
    elements: &[InlineSegment],
) -> docx_rs::Paragraph {
    use docx_rs::*;

    // Coalesce consecutive segments with the same href into one piece so a
    // link spanning multiple format runs renders as a single hyperlink.
    enum Piece {
        Run(Box<Run>),
        Link(String, Vec<Run>),
    }

    let mut pieces: Vec<Piece> = Vec::new();
    for elem in elements {
        let Some(run) = build_run(elem) else {
            continue;
        };
        match &elem.fmt_anchor_href {
            Some(href) if !href.is_empty() => {
                if let Some(Piece::Link(open_href, runs)) = pieces.last_mut()
                    && open_href == href
                {
                    runs.push(run);
                    continue;
                }
                pieces.push(Piece::Link(href.clone(), vec![run]));
            }
            _ => pieces.push(Piece::Run(Box::new(run))),
        }
    }

    for piece in pieces {
        paragraph = match piece {
            Piece::Run(run) => paragraph.add_run(*run),
            Piece::Link(href, runs) => {
                let mut link = Hyperlink::new(href, HyperlinkType::External);
                for run in runs {
                    link = link.add_run(run);
                }
                paragraph.add_hyperlink(link)
            }
        };
    }

    paragraph
}

/// Build a complete abstract-numbering definition (levels 0..=8) for `list`.
///
/// Levels beyond the list's own `indent` are defined too so any nesting level
/// resolves; they all share the list's style.
fn build_abstract_numbering(id: usize, list: &List) -> docx_rs::AbstractNumbering {
    let mut abstract_num = docx_rs::AbstractNumbering::new(id);
    for level in 0..=8usize {
        abstract_num = abstract_num.add_level(build_level(level, list));
    }
    abstract_num
}

/// Build one numbering level for `list` at the given nesting `level`.
fn build_level(level: usize, list: &List) -> docx_rs::Level {
    use docx_rs::*;

    let (format, text) = match list.style {
        ListStyle::Decimal => ("decimal", ordered_level_text(level, list)),
        ListStyle::LowerAlpha => ("lowerLetter", ordered_level_text(level, list)),
        ListStyle::UpperAlpha => ("upperLetter", ordered_level_text(level, list)),
        ListStyle::LowerRoman => ("lowerRoman", ordered_level_text(level, list)),
        ListStyle::UpperRoman => ("upperRoman", ordered_level_text(level, list)),
        ListStyle::Disc => ("bullet", "\u{2022}".to_string()), //        ListStyle::Circle => ("bullet", "\u{25CB}".to_string()), //        ListStyle::Square => ("bullet", "\u{25AA}".to_string()), //    };

    let left = INDENT_STEP_TWIPS * (level as i32 + 1);
    Level::new(
        level,
        Start::new(1),
        NumberFormat::new(format),
        LevelText::new(text),
        LevelJc::new("left"),
    )
    .indent(
        Some(left),
        Some(SpecialIndentType::Hanging(HANGING_TWIPS)),
        None,
        None,
    )
}

/// `LevelText` for an ordered list level, e.g. `"1."` or `"(a)"`, honouring the
/// list's recorded prefix/suffix. The `%N` placeholder is 1-based on the level.
fn ordered_level_text(level: usize, list: &List) -> String {
    let suffix = if list.suffix.is_empty() {
        "."
    } else {
        list.suffix.as_str()
    };
    format!("{}%{}{}", list.prefix, level + 1, suffix)
}