text-document-io 1.9.3

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
// Generated by Qleany v1.4.8 from feature_use_case.tera
use crate::ExportLatexDto;
use crate::ExportLatexResultDto;
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, Root, SemanticRole, Table, TableCell,
    TextDirection,
};
use common::format_runs::InlineContent;
use common::types::{EntityId, ROOT_ENTITY_ID};
use std::collections::HashMap;
use std::collections::HashSet;

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

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

pub struct ExportLatexUseCase {
    uow_factory: Box<dyn ExportLatexUnitOfWorkFactoryTrait>,
    /// Copied off the DTO at the top of `execute`, because the inline renderer
    /// that needs it sits four calls down a walk that threads only the uow and
    /// the block. Mirrors `ExportMarkdownUseCase::options`, which holds its
    /// export settings as a field for the same reason.
    omit_images: bool,
    /// Each note's body, already rendered, by label — for the same reason
    /// `omit_images` is a field: the inline renderer that needs it sits four
    /// calls down a walk threading only the uow and the block.
    ///
    /// LaTeX takes the note's text *at the reference*, not at a definition
    /// site, so the body has to be in hand by the time a marker is written.
    /// That inverts the arrangement DOCX and HTML use and is why this is
    /// pre-rendered rather than emitted where the definition sits.
    note_bodies: std::collections::HashMap<String, String>,
    /// Labels that have already had their real `\footnote{…}` emitted this
    /// export — so a **second** citation of the same label (`footnotes.rs`'s
    /// own invariant: "a label referenced twice keeps one number — it is one
    /// note") reuses that footnote instead of opening a second one under a
    /// second, LaTeX-auto-numbered, duplicated-body footnote. `RefCell`
    /// because `render_inline_latex` only holds `&self`.
    footnoted_labels: std::cell::RefCell<std::collections::HashSet<String>>,
}

impl ExportLatexUseCase {
    pub fn new(uow_factory: Box<dyn ExportLatexUnitOfWorkFactoryTrait>) -> Self {
        ExportLatexUseCase {
            uow_factory,
            omit_images: false,
            note_bodies: std::collections::HashMap::new(),
            footnoted_labels: std::cell::RefCell::new(std::collections::HashSet::new()),
        }
    }

    pub fn execute(&mut self, dto: &ExportLatexDto) -> Result<ExportLatexResultDto> {
        self.omit_images = dto.omit_images;
        let uow = self.uow_factory.create();
        uow.begin_transaction()?;

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

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

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

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

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

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

        // Render every note's body before the prose that cites it. Deliberately
        // before `note_bodies` is populated, so a note citing another note falls
        // back to a bare `\footnotemark` instead of recursing — LaTeX has no
        // nested footnote anyway, and a stack overflow is a poor way to find out.
        self.note_bodies.clear();
        self.footnoted_labels.borrow_mut().clear();
        let mut bodies = std::collections::HashMap::new();
        for (_, label, frame_id) in notes.in_print_order() {
            let body = self.render_frame_latex(&*uow, &frame_id, &cell_frame_ids)?;
            bodies.insert(label, body.trim().to_string());
        }
        self.note_bodies = bodies;

        for frame_id in &frame_ids {
            // Skip cell frames — they're rendered as part of their table
            if cell_frame_ids.contains(frame_id) {
                continue;
            }
            // 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;
            }
            // Skip sub-frames (parent_frame != None) — recursively rendered
            // by their parent's render_frame_latex walk; rendering at the
            // top level again would duplicate their content.
            if let Some(f) = uow.get_frame(frame_id)?
                && f.parent_frame.is_some()
            {
                continue;
            }

            let frame_latex = self.render_frame_latex(&*uow, frame_id, &cell_frame_ids)?;
            if !frame_latex.is_empty() {
                body_parts.push(frame_latex);
            }
        }

        uow.end_transaction()?;

        let body = body_parts.join("\n\n");

        let latex_text = if dto.include_preamble {
            let doc_class = if dto.document_class.is_empty() {
                "article"
            } else {
                &dto.document_class
            };
            // `secnumdepth = -1` turns off LaTeX's own section numbering.
            //
            // A heading reaches this exporter as finished text: a caller that numbers its
            // headings has already composed "Chapter 3 — The Storm" into the string below,
            // and `\section{…}` in a default `article` (secnumdepth 3) would print its own
            // counter in front of it — "1  Chapter 3 — The Storm", two disagreeing numbers
            // side by side, and worse with a Part above, where `\subsection` renumbers per
            // `\section` while the caller's chapter counter does not.
            //
            // Unnumbered rather than starred (`\section*`) on purpose: starring also drops
            // the ToC entry and the running head, which a book wants to keep. This suppresses
            // only the numeral.
            //
            // The Typst backend has carried the same one-line fix since it was written
            // (`typst_markup.rs`: `#set heading(numbering: none)`, "Skribisto composes its
            // own, already-numbered heading text — Typst must not additionally auto-number
            // it"). This is that fix, ported.
            //
            // Body-only output (`include_preamble: false`) is deliberately untouched: the
            // embedding document owns its preamble, and silently rewriting its counters
            // from inside a fragment would be the wrong kind of helpful.
            format!(
                "\\documentclass{{{}}}\n\\usepackage{{hyperref}}\n\\usepackage{{ulem}}\n\\usepackage{{graphicx}}\n\\usepackage{{setspace}}\n\\usepackage{{xcolor}}\n\\setcounter{{secnumdepth}}{{-1}}\n\\begin{{document}}\n\n{}\n\n\\end{{document}}",
                doc_class, body
            )
        } else {
            body
        };

        Ok(ExportLatexResultDto { latex_text })
    }

    fn render_frame_latex(
        &self,
        uow: &dyn ExportLatexUnitOfWorkTrait,
        frame_id: &EntityId,
        cell_frame_ids: &HashSet<EntityId>,
    ) -> Result<String> {
        let frame = uow.get_frame(frame_id)?;
        let frame = match frame {
            Some(f) => f,
            None => return Ok(String::new()),
        };

        // Check if this is a table anchor frame
        if let Some(table_id) = frame.table {
            return self.render_table_latex(uow, &table_id);
        }

        let block_ids = uow.get_frame_relationship(
            frame_id,
            &common::direct_access::frame::FrameRelationshipField::Blocks,
        )?;

        // Build a map of block ID -> Block for quick lookup
        let blocks_opt = uow.get_block_multi(&block_ids)?;
        let block_map: HashMap<EntityId, Block> = blocks_opt
            .into_iter()
            .flatten()
            .map(|b| (b.id, b))
            .collect();

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

        if frame.child_order.is_empty() {
            // No child_order: fall back to rendering all blocks sorted by position
            let mut blocks: Vec<&Block> = block_map.values().collect();
            blocks.sort_by_key(|b| b.document_position);
            self.render_blocks_latex(uow, &blocks, frame.fmt_semantic_role.as_ref(), &mut parts)?;
        } else {
            // Use child_order to interleave blocks and sub-frames
            // Collect consecutive blocks, then render them as a group
            let mut pending_blocks: Vec<&Block> = Vec::new();

            for &order_val in &frame.child_order {
                if order_val > 0 {
                    // Positive = block ID
                    let block_id: EntityId = order_val as u64;
                    if let Some(block) = block_map.get(&block_id) {
                        pending_blocks.push(block);
                    }
                } else {
                    // Negative = negated sub-frame ID
                    // Flush pending blocks first
                    if !pending_blocks.is_empty() {
                        self.render_blocks_latex(
                            uow,
                            &pending_blocks,
                            frame.fmt_semantic_role.as_ref(),
                            &mut parts,
                        )?;
                        pending_blocks.clear();
                    }

                    let sub_frame_id: EntityId = (-order_val) as u64;
                    // Skip cell frames
                    if cell_frame_ids.contains(&sub_frame_id) {
                        continue;
                    }
                    let sub_latex = self.render_frame_latex(uow, &sub_frame_id, cell_frame_ids)?;
                    if !sub_latex.is_empty() {
                        parts.push(sub_latex);
                    }
                }
            }

            // Flush remaining pending blocks
            if !pending_blocks.is_empty() {
                self.render_blocks_latex(
                    uow,
                    &pending_blocks,
                    frame.fmt_semantic_role.as_ref(),
                    &mut parts,
                )?;
            }
        }

        if parts.is_empty() {
            return Ok(String::new());
        }

        let content = parts.join("\n\n");

        // Wrap with blockquote environment if applicable
        if frame.fmt_is_blockquote == Some(true) {
            Ok(format!("\\begin{{quote}}\n{}\n\\end{{quote}}", content))
        } else {
            Ok(content)
        }
    }

    /// Render a sequence of blocks (handling list grouping, code blocks, etc.)
    fn render_blocks_latex(
        &self,
        uow: &dyn ExportLatexUnitOfWorkTrait,
        blocks: &[&Block],
        semantic: Option<&SemanticRole>,
        parts: &mut Vec<String>,
    ) -> Result<()> {
        let mut i = 0;
        while i < blocks.len() {
            let block = blocks[i];

            // Its own entry in `parts` (they are joined with a blank line), so it can
            // never end up glued to the front of a `\\section{…}` and swallow it.
            if block.fmt_page_break_before == Some(true) {
                parts.push("\\newpage".to_string());
            }

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

            if let Some(ref list_entity) = list {
                // Collect consecutive list items
                let is_ordered = matches!(
                    list_entity.style,
                    ListStyle::Decimal
                        | ListStyle::LowerAlpha
                        | ListStyle::UpperAlpha
                        | ListStyle::LowerRoman
                        | ListStyle::UpperRoman
                );
                let env = if is_ordered { "enumerate" } else { "itemize" };
                let mut items = Vec::new();

                while i < blocks.len() {
                    let b = blocks[i];
                    let b_list_ids = uow.get_block_relationship(
                        &b.id,
                        &common::direct_access::block::BlockRelationshipField::List,
                    )?;
                    let b_list = if let Some(lid) = b_list_ids.first() {
                        uow.get_list(lid)?
                    } else {
                        None
                    };

                    // A run becomes one `itemize`/`enumerate`, so a page break inside
                    // it has nowhere to go — end the run and let the outer loop emit it.
                    if b_list.is_some()
                        && (b.fmt_page_break_before != Some(true) || items.is_empty())
                    {
                        let inline_latex = self.render_inline_latex(uow, b)?;
                        items.push(format!("\\item {}", inline_latex));
                        i += 1;
                    } else {
                        break;
                    }
                }

                parts.push(format!(
                    "\\begin{{{}}}\n{}\n\\end{{{}}}",
                    env,
                    items.join("\n"),
                    env
                ));
            } else if block.fmt_is_code_block == Some(true) {
                // Code block: emit verbatim with raw text (no LaTeX formatting)
                let raw_text = self.render_raw_text(uow, block)?;
                parts.push(format!(
                    "\\begin{{verbatim}}\n{}\n\\end{{verbatim}}",
                    raw_text
                ));
                i += 1;
            } else {
                let inline_latex = self.render_inline_latex(uow, block)?;

                let mut content = if let Some(level) = block.fmt_heading_level {
                    let cmd = match level {
                        1 => "section",
                        2 => "subsection",
                        3 => "subsubsection",
                        _ => "paragraph",
                    };
                    format!("\\{}{{{}}}", cmd, inline_latex)
                } else {
                    inline_latex
                };

                // The block's own space-above — the gap a blank-line scene break opens, and
                // the drop that puts a title page's title a third of the way down. Never
                // emitted here before, so both were silently flat. `\vspace*` rather than
                // `\vspace`, since the starred form is not discarded at a page break, and
                // that is the one place the space is load-bearing. 96 px to the inch, 72 pt
                // to the inch.
                if let Some(tm) = block.fmt_top_margin.filter(|&t| t > 0) {
                    content = format!("\\vspace*{{{:.1}pt}}\n{}", tm as f64 * 0.75, content);
                }

                // Alignment. LaTeX's default is justified-with-ragged-bottom, so Left
                // and Justify need no environment; only the two that actually move the
                // text do. Emitted before the wraps below so `\\setstretch` and friends
                // apply inside the alignment group, not the other way round.
                match block.fmt_alignment {
                    Some(Alignment::Center) => {
                        content = format!("\\begin{{center}}\n{}\n\\end{{center}}", content);
                    }
                    Some(Alignment::Right) => {
                        content =
                            format!("\\begin{{flushright}}\n{}\n\\end{{flushright}}", content);
                    }
                    Some(Alignment::Left) | Some(Alignment::Justify) | None => {}
                }

                // An epigraph's quotation is set in italics and its attribution is not
                // — the same split every sibling writer makes, and decided the same way:
                // by the right alignment the author already gave the source line. Applied
                // before the alignment wrap so the italics stay inside the group.
                if let Some(SemanticRole::Epigraph) = semantic
                    && block.fmt_alignment != Some(Alignment::Right)
                {
                    content = format!("{{\\itshape {}}}", content);
                }

                // Wrap with line-height
                if let Some(lh) = block.fmt_line_height {
                    let spacing = lh as f64 / 1000.0;
                    content = format!("{{\\setstretch{{{:.2}}}{}}}", spacing, content);
                }
                // Wrap with direction
                if block.fmt_direction == Some(TextDirection::RightToLeft) {
                    content = format!("\\RL{{{}}}", content);
                }
                // Wrap with background color
                if let Some(ref c) = block.fmt_background_color {
                    content = format!(
                        "\\colorbox{{{}}}{{\\parbox{{\\linewidth}}{{{}}}}}",
                        c, content
                    );
                }
                // Wrap with non-breakable lines
                if block.fmt_non_breakable_lines == Some(true) {
                    content = format!("\\mbox{{{}}}", content);
                }

                parts.push(content);
                i += 1;
            }
        }

        Ok(())
    }

    /// Render raw text content of a block (no LaTeX escaping or formatting).
    /// Used for verbatim/code block environments.
    fn render_raw_text(
        &self,
        uow: &dyn ExportLatexUnitOfWorkTrait,
        block: &Block,
    ) -> Result<String> {
        let block_text = block_content_via_store(block, &uow.store());
        let elements = common::format_runs_query::inline_segments_for_block(
            &uow.store(),
            block.id,
            &block_text,
        );

        let mut text = String::new();
        for elem in &elements {
            match &elem.content {
                InlineContent::Text(t) => text.push_str(t),
                // Plain-text extraction of a block: an image has no textual
                // form, so its description is the only honest substitute. The
                // filename was being emitted here, which put a path into prose.
                InlineContent::Image { alt, .. } => text.push_str(alt),
                // A reference's marker is generated by the format, not carried
                // as prose, so a plain-text extraction of the block has
                // nothing to take from it.
                InlineContent::FootnoteRef { .. } => {}
                InlineContent::Empty => {}
            }
        }

        Ok(text)
    }

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

        let mut latex = String::new();

        for elem in &elements {
            let text = match &elem.content {
                InlineContent::Text(t) => escape_latex(t),
                // `\footnote{…}` carries the note's text at the reference,
                // which is where LaTeX puts it — no definition site, no label.
                // A reference whose body this document does not hold falls back
                // to `\footnotemark`, LaTeX's own primitive for a marker whose
                // text is supplied elsewhere: it still auto-numbers, so the
                // sequence a reader sees stays right.
                //
                // A **second** citation of a label that does have a body must
                // not open a second `\footnote{…}`: LaTeX would auto-number that
                // as a brand-new note, duplicating the text under two different
                // numbers — exactly the "one note, one number" invariant
                // `footnotes.rs` documents. So only the first sighting defines
                // the footnote (and `\label`s it under a safe, collision-proof
                // id — see `safe_label_id`); every later sighting reuses it via
                // `\footnotemark[\getrefnumber{…}]`, the standard `hyperref`
                // idiom for "the mark of a footnote defined elsewhere" (already
                // a dependency here for `\href`, so this adds no new package).
                InlineContent::FootnoteRef { label } => {
                    match self.note_bodies.get(label) {
                        Some(body) => {
                            let anchor = crate::footnotes::safe_label_id(label);
                            if self.footnoted_labels.borrow_mut().insert(label.clone()) {
                                let body_with_label = format!("{body}\\label{{{anchor}}}");
                                latex.push_str(&format!("\\footnote{{{body_with_label}}}"));
                            } else {
                                latex.push_str(&format!(
                                    "\\footnotemark[\\getrefnumber{{{anchor}}}]"
                                ));
                            }
                        }
                        None => latex.push_str("\\footnotemark{}"),
                    }
                    continue;
                }
                InlineContent::Image {
                    name,
                    width,
                    height,
                    ..
                } => {
                    if self.omit_images {
                        String::new()
                    } else {
                        // LaTeX resolves `\includegraphics` against the filesystem at
                        // compile time, so the `src` is emitted as the document
                        // stores it and placing the file beside the `.tex` is the
                        // caller's job — this crate writes no files. `graphicx` is
                        // already in the emitted preamble.
                        //
                        // Sizes are in `bp` (big points, 1/72") because the model's
                        // dimensions are logical pixels at 96 dpi; LaTeX's own `pt`
                        // is 1/72.27" and would be silently ~0.4% off.
                        let mut opts = Vec::new();
                        if *width > 0 {
                            opts.push(format!("width={}bp", *width as f64 * 0.75));
                        }
                        if *height > 0 {
                            opts.push(format!("height={}bp", *height as f64 * 0.75));
                        }
                        if opts.is_empty() {
                            format!("\\includegraphics{{{}}}", escape_latex(name))
                        } else {
                            format!(
                                "\\includegraphics[{}]{{{}}}",
                                opts.join(","),
                                escape_latex(name)
                            )
                        }
                    }
                }
                InlineContent::Empty => String::new(),
            };

            if text.is_empty() {
                continue;
            }

            // Check if already an \includegraphics command
            if text.starts_with("\\includegraphics") {
                latex.push_str(&text);
                continue;
            }

            let mut formatted = text;

            if elem.fmt_font_family.as_deref() == Some("monospace") {
                formatted = format!("\\texttt{{{}}}", formatted);
            }
            if elem.fmt_font_bold == Some(true) {
                formatted = format!("\\textbf{{{}}}", formatted);
            }
            if elem.fmt_font_italic == Some(true) {
                formatted = format!("\\textit{{{}}}", formatted);
            }
            if elem.fmt_font_underline == Some(true) {
                formatted = format!("\\underline{{{}}}", formatted);
            }
            if elem.fmt_font_strikeout == Some(true) {
                formatted = format!("\\sout{{{}}}", formatted);
            }
            if let Some(ref href) = elem.fmt_anchor_href {
                formatted = format!("\\href{{{}}}{{{}}}", escape_latex(href), formatted);
            }

            latex.push_str(&formatted);
        }

        Ok(latex)
    }

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

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

        let rows = table.rows as usize;
        let cols = table.columns as usize;
        let mut covered = vec![vec![false; cols]; rows];

        // Build column spec: |l|l|...|l|
        let col_spec = format!("|{}|", vec!["l"; cols].join("|"));
        let mut latex = format!("\\begin{{tabular}}{{{}}}\n\\hline", col_spec);

        for r in 0..rows {
            let mut row_parts: Vec<String> = Vec::new();
            let mut c = 0;
            while c < cols {
                if covered[r][c] {
                    c += 1;
                    continue;
                }

                // Find the cell at this position
                let cell = cells
                    .iter()
                    .find(|cell| cell.row == r as i64 && cell.column == c as i64);

                if let Some(cell) = cell {
                    // Get cell content
                    let content = if let Some(cf_id) = cell.cell_frame {
                        let block_ids = uow.get_frame_relationship(
                            &cf_id,
                            &common::direct_access::frame::FrameRelationshipField::Blocks,
                        )?;
                        let blocks_opt = uow.get_block_multi(&block_ids)?;
                        let blocks: Vec<Block> = blocks_opt.into_iter().flatten().collect();

                        let mut cell_parts: Vec<String> = Vec::new();
                        for block in &blocks {
                            let inline_latex = self.render_inline_latex(uow, block)?;
                            if !inline_latex.is_empty() {
                                cell_parts.push(inline_latex);
                            }
                        }
                        cell_parts.join(" ")
                    } else {
                        String::new()
                    };

                    // Wrap content with \multirow and/or \multicolumn as needed
                    let wrapped = if cell.row_span > 1 && cell.column_span > 1 {
                        let cs = cell.column_span as usize;
                        let rs = cell.row_span as usize;
                        for sc in 1..cs {
                            if c + sc < cols {
                                covered[r][c + sc] = true;
                            }
                        }
                        format!(
                            "\\multicolumn{{{}}}{{|l|}}{{\\multirow{{{}}}{{*}}{{{}}}}}",
                            cs, rs, content
                        )
                    } else if cell.column_span > 1 {
                        let cs = cell.column_span as usize;
                        for sc in 1..cs {
                            if c + sc < cols {
                                covered[r][c + sc] = true;
                            }
                        }
                        format!("\\multicolumn{{{}}}{{|l|}}{{{}}}", cs, content)
                    } else if cell.row_span > 1 {
                        let rs = cell.row_span as usize;
                        format!("\\multirow{{{}}}{{*}}{{{}}}", rs, content)
                    } else {
                        content
                    };
                    row_parts.push(wrapped);

                    // Mark row-spanned cells as covered
                    for sr in 1..cell.row_span as usize {
                        for sc in 0..cell.column_span as usize {
                            if r + sr < rows && c + sc < cols {
                                covered[r + sr][c + sc] = true;
                            }
                        }
                    }

                    c += cell.column_span as usize;
                } else {
                    row_parts.push(String::new());
                    c += 1;
                }
            }

            latex.push_str(&format!("\n{} \\\\", row_parts.join(" & ")));
            latex.push_str("\n\\hline");
        }

        latex.push_str("\n\\end{tabular}");
        Ok(latex)
    }
}

fn escape_latex(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '\\' => result.push_str("\\textbackslash{}"),
            '&' => result.push_str("\\&"),
            '%' => result.push_str("\\%"),
            '$' => result.push_str("\\$"),
            '#' => result.push_str("\\#"),
            '_' => result.push_str("\\_"),
            '{' => result.push_str("\\{"),
            '}' => result.push_str("\\}"),
            '~' => result.push_str("\\textasciitilde{}"),
            '^' => result.push_str("\\textasciicircum{}"),
            _ => result.push(ch),
        }
    }
    result
}