text-document-io 1.7.0

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

impl ExportLatexUseCase {
    pub fn new(uow_factory: Box<dyn ExportLatexUnitOfWorkFactoryTrait>) -> Self {
        ExportLatexUseCase { uow_factory }
    }

    pub fn execute(&mut self, dto: &ExportLatexDto) -> Result<ExportLatexResultDto> {
        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();

        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 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
            };
            format!(
                "\\documentclass{{{}}}\n\\usepackage{{hyperref}}\n\\usepackage{{ulem}}\n\\usepackage{{graphicx}}\n\\usepackage{{setspace}}\n\\usepackage{{xcolor}}\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, &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, &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, &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],
        parts: &mut Vec<String>,
    ) -> Result<()> {
        let mut i = 0;
        while i < blocks.len() {
            let block = blocks[i];

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

                    if b_list.is_some() {
                        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
                };

                // 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),
                InlineContent::Image { name, .. } => text.push_str(name),
                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),
                InlineContent::Image { name, .. } => {
                    format!("\\includegraphics{{{}}}", 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
}