text-document-io 1.9.2

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
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
// 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, SemanticRole, Table,
    TableCell,
};
use common::format_runs::{InlineContent, InlineSegment};
use common::long_operation::LongOperation;
use common::parser_tools::ExportImages;
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 {}

/// Each note's body as finished paragraphs, by label.
///
/// OOXML carries a footnote's text inside the run that references it, so the
/// body has to be in hand by the time a marker is built — the same inversion
/// LaTeX has, and why both pre-render rather than emitting at a definition site.
type NoteParagraphs = std::collections::HashMap<String, Vec<docx_rs::Paragraph>>;

/// What `build_run` needs to render a footnote reference correctly the
/// *second* time a label is cited.
///
/// OOXML has no construct for "the same footnote, cited again" through this
/// library: `docx-rs`'s `Docx::collect_footnotes()` turns *every*
/// `<w:footnoteReference>` it finds anywhere in the run tree into its own
/// `<w:footnote>` entry, unconditionally — so a second `add_footnote_reference`
/// call for a label already defined would not reuse that note, it would emit a
/// **second** `<w:footnote>` (duplicating the body) and, worse, share the first
/// one's `w:id`, which OOXML does not allow two definitions to share. So only
/// the label's first citation becomes a real, native footnote; a repeat prints
/// a plain run carrying the same number that citation already earned —
/// `numbers`' own reading-order marker table, styled with Word's built-in
/// `"FootnoteReference"` character style so it still *looks* like a footnote
/// mark, just without a second, duplicate definition underneath it.
struct FootnoteRefState<'a> {
    numbers: &'a crate::footnotes::Footnotes,
    /// Labels whose real `<w:footnoteReference>` has already been emitted —
    /// scoped to ONE pass over the document (a fresh, throwaway state per note
    /// while pre-rendering note bodies, the shared one for the main walk — see
    /// `build_docx`) so a nested citation inside one note's body can never be
    /// mistaken for the label's real, resolved citation out in the manuscript,
    /// which would silently swap a note's real content for a bare marker.
    emitted: std::cell::RefCell<std::collections::HashSet<String>>,
}

impl<'a> FootnoteRefState<'a> {
    fn new(numbers: &'a crate::footnotes::Footnotes) -> Self {
        FootnoteRefState {
            numbers,
            emitted: std::cell::RefCell::new(std::collections::HashSet::new()),
        }
    }
}

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;

/// Word style ids for an epigraph's two paragraph kinds. Ids, not display names: the id is
/// what a paragraph references, the name is what the style panel shows.
const EPIGRAPH_STYLE_ID: &str = "Epigraph";
const EPIGRAPH_ATTRIBUTION_STYLE_ID: &str = "EpigraphAttribution";

/// 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;

/// Twips per logical pixel. `Block::fmt_top_margin` / `fmt_text_indent` are in
/// the document model's own unit — logical (CSS) pixels at 96 dpi, matching the
/// editor's layout engine — so 1440/96 = 15 twips per px.
const TWIPS_PER_PX: i64 = 15;

/// Convert a block's logical-pixel spacing to twips, clamped.
///
/// These values come from a `{key=value}` block attribute in the document, so
/// they are file-controlled and may be absurd. Doing the arithmetic in `i64` and
/// clamping at the end is what keeps a huge value from wrapping through `i32`
/// into a negative — and then into an enormous `u32` — instead of saturating.
fn px_to_twips(px: i64) -> i32 {
    px.saturating_mul(TWIPS_PER_PX).clamp(0, i32::MAX as i64) as i32
}

/// 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 notes = crate::footnotes::Footnotes::build(&uow.store());

        // Render every note's body first, while `note_paragraphs` is still
        // empty — so a note that cites another note produces an empty inner
        // footnote rather than recursing. Word has no nested footnote either.
        let note_paragraphs: NoteParagraphs = {
            let mut built: NoteParagraphs = std::collections::HashMap::new();
            let mut note_numbering = NumberingBuilder::default();
            for (_, label, frame_id) in notes.in_print_order() {
                let block_ids = uow.get_frame_relationship(
                    &frame_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 paragraphs = Vec::with_capacity(blocks.len());
                // A throwaway state, scoped to this ONE note's own body — never
                // the shared main-walk state below. A citation found in here is
                // necessarily nested (inside a definition frame), so it must
                // never be marked "emitted" against the label's real, resolved
                // citation out in the manuscript; doing so would make that real
                // citation look like a repeat and silently swap its footnote for
                // a bare marker with no note underneath it.
                let body_footnote_state = FootnoteRefState::new(&notes);
                for block in &blocks {
                    paragraphs.push(self.render_block(
                        uow,
                        block,
                        0,
                        None,
                        &mut note_numbering,
                        &std::collections::HashMap::new(),
                        &body_footnote_state,
                    )?);
                }
                built.insert(label, paragraphs);
            }
            built
        };

        let mut numbering = NumberingBuilder::default();
        let mut elements: Vec<DocxElement> = Vec::new();
        // Shared across the WHOLE main walk (every top-level frame, every
        // table cell reached from it): a label's real footnote must be
        // defined at most once across the entire document, not once per frame.
        let footnote_state = FootnoteRefState::new(&notes);

        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;
            };

            // 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 notes.is_definition(frame.id) {
                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,
                    &note_paragraphs,
                    &footnote_state,
                )?;
                elements.push(DocxElement::Table(Box::new(table)));
                continue;
            }

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

            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();
        // Real named styles, so an epigraph is restylable in Word's style panel rather
        // than being a paragraph that merely happens to be indented. Declared always:
        // an unused style costs a few bytes and a conditional declaration is one more
        // thing to get out of step with the paragraphs that reference it.
        docx = docx
            .add_style(
                Style::new(EPIGRAPH_STYLE_ID, StyleType::Paragraph)
                    .name("Epigraph")
                    .italic()
                    .indent(Some(INDENT_STEP_TWIPS), None, None, None),
            )
            .add_style(
                Style::new(EPIGRAPH_ATTRIBUTION_STYLE_ID, StyleType::Paragraph)
                    .name("Epigraph Attribution")
                    .indent(Some(INDENT_STEP_TWIPS), None, None, None)
                    .align(AlignmentType::Right),
            );
        // …and the heading styles the heading paragraphs below reference by id. docx-rs
        // ships no built-in styles at all, so without this every `Heading1` in the file is
        // a dangling reference the reader resolves from its own catalogue — which is how a
        // book title asked to be a title and arrived as whatever Word had lying around.
        for (i, h) in self
            .dto
            .options
            .resolved_heading_styles()
            .iter()
            .enumerate()
        {
            docx = docx.add_style(heading_style(i + 1, h));
        }
        // 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,
        semantic: Option<&SemanticRole>,
        numbering: &mut NumberingBuilder,
        notes: &NoteParagraphs,
        cancel_flag: Option<&AtomicBool>,
        out: &mut Vec<DocxElement>,
        footnote_state: &FootnoteRefState,
    ) -> 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,
                            semantic,
                            numbering,
                            notes,
                            footnote_state,
                        )?;
                        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,
                                notes,
                                footnote_state,
                            )?;
                            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
                        };
                        let sub_semantic = if sub_frame.fmt_is_blockquote == Some(true) {
                            sub_frame.fmt_semantic_role.as_ref()
                        } else {
                            semantic
                        };
                        self.render_frame_content(
                            uow,
                            &sub_frame,
                            cell_frame_ids,
                            sub_depth,
                            sub_semantic,
                            numbering,
                            notes,
                            cancel_flag,
                            out,
                            footnote_state,
                        )?;
                    }
                }
            }
        } 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,
                    semantic,
                    numbering,
                    notes,
                    footnote_state,
                )?;
                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.
    #[allow(clippy::too_many_arguments)]
    fn render_block(
        &self,
        uow: &dyn ExportDocxUnitOfWorkTrait,
        block: &Block,
        quote_depth: usize,
        semantic: Option<&SemanticRole>,
        numbering: &mut NumberingBuilder,
        notes: &NoteParagraphs,
        footnote_state: &FootnoteRefState,
    ) -> 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);
        }
        // Set here, in the common section, so it survives whichever of the three branches
        // below claims the block: `<w:pageBreakBefore/>` and `<w:pStyle/>` are independent
        // children of `<w:pPr>`, so applying a style afterwards cannot drop it.
        if block.fmt_page_break_before == Some(true) {
            paragraph = paragraph.page_break_before(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);
            }
            // A heading does not take the document's body spacing — its style carries its
            // own — but its *own* space-above is a block-level instruction and has to
            // survive, because that is how a title page drops its title down the page.
            // `apply_body_style` handles this for ordinary paragraphs; a heading never
            // reaches it.
            if let Some(before) = block.fmt_top_margin.filter(|&t| t > 0) {
                let mut ls = LineSpacing::new().before(px_to_twips(before) as u32);
                if let Some(lh) = block.fmt_line_height {
                    ls = ls
                        .line_rule(LineSpacingType::Auto)
                        .line((lh as f64 / 1000.0 * 240.0) as i32);
                }
                paragraph = paragraph.line_spacing(ls);
            }
        } 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);
            // An epigraph's paragraphs carry its named style. Which of the two is
            // decided by the alignment the author already gave the line: the attribution
            // is the right-aligned one, which is the convention the editor writes and
            // every other writer renders — so nothing extra has to be recorded to tell
            // a quotation's last line from its source line.
            if let Some(SemanticRole::Epigraph) = semantic {
                paragraph = paragraph.style(if block.fmt_alignment == Some(Alignment::Right) {
                    EPIGRAPH_ATTRIBUTION_STYLE_ID
                } else {
                    EPIGRAPH_STYLE_ID
                });
            }
        }

        Ok(add_inline_content(
            paragraph,
            &elements,
            &self.dto.options.images,
            notes,
            footnote_state,
        ))
    }

    /// 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;
        }
        // A block's own space-above, e.g. the gap a blank-line scene break puts
        // before the paragraph that follows it. Stacks with the document-wide
        // space-after of the previous paragraph rather than replacing it.
        if let Some(before) = block.fmt_top_margin.filter(|&t| t > 0) {
            ls = ls.before(px_to_twips(before) as u32);
            ls_used = true;
        }
        if ls_used {
            p = p.line_spacing(ls);
        }

        // Indent: any blockquote left indent + a first-line indent. A block that
        // carries its own `fmt_text_indent` overrides the document-wide default,
        // which is how a scene break suppresses the indent on the next paragraph
        // (`text_indent=0`) exactly as print typography expects.
        let first_line = match block.fmt_text_indent {
            Some(ti) => (ti > 0).then(|| px_to_twips(ti)),
            None => 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,
        notes: &NoteParagraphs,
        footnote_state: &FootnoteRefState,
    ) -> 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,
                            None,
                            numbering,
                            notes,
                            None,
                            &mut cell_elements,
                            footnote_state,
                        )?;
                        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,
    }
}

/// Build the `HeadingN` paragraph style definition for one level.
///
/// `outline_lvl` is what makes the result more than cosmetic: it is the field Word's
/// navigation pane and its automatic table of contents both read, so a document whose
/// headings carry it becomes navigable rather than merely large-and-bold.
fn heading_style(level: usize, h: &common::parser_tools::DocxHeadingStyle) -> docx_rs::Style {
    use docx_rs::*;
    let mut style = Style::new(format!("Heading{level}"), StyleType::Paragraph)
        .name(format!("heading {level}"))
        // Zero-based, and clamped to Word's nine outline levels.
        .outline_lvl(level.clamp(1, 9) - 1);
    if let Some(size) = h.size_half_points {
        style = style.size(size);
    }
    if h.bold {
        style = style.bold();
    }
    if h.italic {
        style = style.italic();
    }
    if let Some(a) = &h.alignment {
        style = style.align(map_alignment(a));
    }
    if h.space_before_twips.is_some() || h.space_after_twips.is_some() {
        let mut ls = LineSpacing::new();
        if let Some(before) = h.space_before_twips {
            ls = ls.before(before.max(0) as u32);
        }
        if let Some(after) = h.space_after_twips {
            ls = ls.after(after.max(0) as u32);
        }
        style = style.line_spacing(ls);
    }
    // `Style` exposes no builder for these two, but its `paragraph_property` is public
    // and *is* written out by its XML builder — the same door `render_block` already
    // goes through for `bidi`.
    if h.keep_with_next {
        style.paragraph_property = style.paragraph_property.keep_next(true);
    }
    if h.page_break_before {
        style.paragraph_property = style.paragraph_property.page_break_before(true);
    }
    style
}

/// 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
}

/// Embed an inline image as a real DOCX drawing.
///
/// Returns `None` when the caller supplied no bytes for this `src`, or when
/// those bytes are not a decodable image — the run then falls back to alt text.
/// An unreadable picture must never fail a manuscript export.
///
/// **Why the image is re-encoded as PNG.** docx-rs writes every embedded image
/// to `word/media/{id}.png` (`image_collector.rs`) regardless of what the bytes
/// actually are, so handing it a JPEG produces a package whose part is named and
/// typed `png` but contains JPEG — a file Word refuses to render. Its own
/// `Pic::new` avoids that by transcoding through the `image` crate, but it
/// `.expect()`s on a decode failure, which would turn a corrupt user file into a
/// panic. This does the same conversion fallibly.
fn build_image_run(
    name: &str,
    alt: &str,
    width: i64,
    height: i64,
    images: &ExportImages,
) -> Option<docx_rs::Run> {
    use docx_rs::*;
    use image::GenericImageView;

    let bytes = &images.get(name)?.bytes;
    let decoded = image::load_from_memory(bytes).ok()?;
    let (natural_w, natural_h) = decoded.dimensions();

    let mut png = std::io::Cursor::new(Vec::new());
    decoded.write_to(&mut png, image::ImageFormat::Png).ok()?;

    // OOXML measures drawings in EMUs: 914400 per inch, and a pixel is 1/96".
    // Display size, when the document carries one, wins over the file's own
    // dimensions — that is what a resize in the editor means.
    const EMU_PER_PX: u32 = 9525;
    let display_w = if width > 0 { width as u32 } else { natural_w };
    let display_h = if height > 0 { height as u32 } else { natural_h };

    let pic = Pic::new_with_dimensions(png.into_inner(), natural_w, natural_h)
        .size(display_w * EMU_PER_PX, display_h * EMU_PER_PX);

    // ⚠ Alt text is lost here, and cannot currently be preserved: OOXML carries
    // it on `wp:docPr/@descr`, but docx-rs's builder for that element accepts
    // only `id` and `name` (`xml_builder/drawing.rs`). Emitting it as an
    // adjacent text run was considered and rejected — it would print the
    // description into the manuscript. Fixing this properly needs an upstream
    // change; until then a DOCX export is the one backend where an image's
    // description does not travel.
    let _ = alt;

    Some(Run::new().add_image(pic))
}

/// 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,
    images: &ExportImages,
    notes: &std::collections::HashMap<String, Vec<docx_rs::Paragraph>>,
    footnote_state: &FootnoteRefState,
) -> Option<docx_rs::Run> {
    use docx_rs::*;

    // A real OOXML footnote: Word numbers it, places it at the foot of the page
    // it lands on, and renumbers when the text reflows. A reference whose body
    // this document does not hold still gets its note — an empty one — because
    // dropping the run entirely would delete the marker from the sentence.
    //
    // That is the FIRST citation of a label. A repeat must not go through here
    // again — see `FootnoteRefState`'s doc for why a second
    // `add_footnote_reference` call would corrupt, not duplicate, the package.
    // It gets a plain run instead, carrying the number the first citation
    // already earned, styled as "FootnoteReference" so it still reads as a
    // footnote mark even though it opens no second note.
    if let InlineContent::FootnoteRef { label } = &elem.content {
        if footnote_state.emitted.borrow_mut().insert(label.clone()) {
            let mut footnote = Footnote::new();
            for paragraph in notes.get(label).cloned().unwrap_or_default() {
                footnote = footnote.add_content(paragraph);
            }
            return Some(Run::new().add_footnote_reference(footnote));
        }
        let marker = footnote_state.numbers.marker(label);
        let mut run = Run::new().add_text(marker);
        run.run_property = run.run_property.style("FootnoteReference");
        return Some(run);
    }

    let text = match &elem.content {
        // Handled above, before any of the text machinery: a reference has no
        // text of its own, and its whole rendering is the run it returns there.
        InlineContent::FootnoteRef { .. } => return None,
        InlineContent::Text(t) => t.clone(),
        InlineContent::Image {
            name,
            alt,
            width,
            height,
            ..
        } => {
            if let Some(run) = build_image_run(name, alt, *width, *height, images) {
                return Some(run);
            }
            // No bytes, or undecodable: degrade to the description rather than
            // to a bracketed filename, which means nothing to a reader.
            if alt.is_empty() {
                return None;
            }
            alt.clone()
        }
        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],
    images: &ExportImages,
    notes: &std::collections::HashMap<String, Vec<docx_rs::Paragraph>>,
    footnote_state: &FootnoteRefState,
) -> 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, images, notes, footnote_state) 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)
}