rtex 0.1.11

Native TeX to PDF converter written in Rust with zero external LaTeX dependencies
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
//! LaTeX AST → [pdfrs](https://crates.io/crates/pdfrs) element conversion and PDF rendering.

use std::path::PathBuf;

use pdfrs::elements::{Element, TableAlignment, TextSegment};
use pdfrs::optimization::{OptimizationProfile, OptimizedPdfGenerator};
use pdfrs::pdf_generator::{AccessibilityOptions, PageLayout as PdfrsLayout};

use crate::error::LatexError;
use crate::parser::{MathLineKind, TexElement};
use crate::table::{Align, Table};

/// Rasterize an SVG file to a PNG temp file and return the temp path.
/// Returns the original path unchanged if it is not an SVG.
/// Uses a random UUID for the temp filename to avoid collisions under
/// parallel conversion.
fn rasterize_svg_if_needed(path: &str, base_dir: Option<&std::path::Path>) -> String {
    let resolved = if std::path::Path::new(path).is_absolute() {
        PathBuf::from(path)
    } else if let Some(base) = base_dir {
        base.join(path)
    } else {
        PathBuf::from(path)
    };

    let is_svg = resolved
        .extension()
        .and_then(|e| e.to_str())
        .is_some_and(|e| e.eq_ignore_ascii_case("svg"));

    if !is_svg {
        return path.to_string();
    }

    let svg_data = match std::fs::read(&resolved) {
        Ok(d) => d,
        Err(_) => return path.to_string(),
    };

    let opt = usvg::Options::default();
    let tree = match usvg::Tree::from_data(&svg_data, &opt) {
        Ok(t) => t,
        Err(_) => return path.to_string(),
    };
    let size = tree.size();
    let width = size.width().ceil().max(1.0) as u32;
    let height = size.height().ceil().max(1.0) as u32;

    let mut pixmap = match resvg::tiny_skia::Pixmap::new(width, height) {
        Some(p) => p,
        None => return path.to_string(),
    };
    resvg::render(
        &tree,
        resvg::tiny_skia::Transform::default(),
        &mut pixmap.as_mut(),
    );

    let rgba = pixmap.data();
    let mut rgb = Vec::with_capacity((width * height * 3) as usize);
    for chunk in rgba.chunks_exact(4) {
        let a = chunk[3] as f32 / 255.0;
        rgb.push((chunk[0] as f32 * a + 255.0 * (1.0 - a)) as u8);
        rgb.push((chunk[1] as f32 * a + 255.0 * (1.0 - a)) as u8);
        rgb.push((chunk[2] as f32 * a + 255.0 * (1.0 - a)) as u8);
    }

    let mut png_buf = Vec::new();
    {
        let mut encoder = png::Encoder::new(&mut png_buf, width, height);
        encoder.set_color(png::ColorType::Rgb);
        encoder.set_depth(png::BitDepth::Eight);
        let mut writer = encoder.write_header().unwrap();
        writer.write_image_data(&rgb).unwrap();
    }

    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let tmp_path = std::env::temp_dir().join(format!(
        "rtex_svg_{}_{}.png",
        std::process::id(),
        COUNTER.fetch_add(1, Ordering::Relaxed)
    ));
    if std::fs::write(&tmp_path, &png_buf).is_err() {
        return path.to_string();
    }
    tmp_path.to_string_lossy().into_owned()
}

/// Maximum mapped element count allowed by the pdfrs renderer.
pub const PDFRS_MAX_ELEMENTS: usize = 5_000;

/// Identifies the pdfrs PDF engine as the only PDF backend.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PdfBackend {
    /// Vendored [pdfrs](https://crates.io/crates/pdfrs) layout engine.
    Pdfrs,
}

impl PdfBackend {
    pub fn producer_label(self) -> &'static str {
        "rtex/pdfrs"
    }
}

/// Document metadata extracted from `\title`, `\author`, `\date`.
#[derive(Debug, Default, Clone)]
pub struct DocumentPdfMeta {
    pub title: Option<String>,
    pub author: Option<String>,
    pub date: Option<String>,
}

/// Extract title/author/date from the element stream.
pub fn extract_document_meta(elements: &[TexElement]) -> DocumentPdfMeta {
    let mut meta = DocumentPdfMeta::default();
    for elem in elements {
        if let TexElement::Command { name, args } = elem {
            match name.as_str() {
                "title" if !args.is_empty() => meta.title = Some(args[0].clone()),
                "author" if !args.is_empty() => meta.author = Some(args[0].clone()),
                "date" if !args.is_empty() => meta.date = Some(args[0].clone()),
                _ => {}
            }
        }
    }
    meta
}

/// Map a LaTeX element tree to pdfrs document elements.
pub fn tex_to_pdfrs_elements(
    elements: &[TexElement],
    image_base_dir: Option<&std::path::Path>,
) -> Vec<Element> {
    let mut writer = ElementWriter::new();
    for element in elements {
        push_tex_element(element, &mut writer, 0, image_base_dir);
    }
    writer.finish()
}

/// Map elements and prepend title-page metadata for pdfrs.
#[cfg_attr(not(test), allow(dead_code))]
pub fn tex_to_pdfrs_document(elements: &[TexElement]) -> Vec<Element> {
    tex_to_pdfrs_document_with_base(elements, None)
}

/// Like [`tex_to_pdfrs_document`] but resolves/rasterizes SVG images using `image_base_dir`.
pub fn tex_to_pdfrs_document_with_base(
    elements: &[TexElement],
    image_base_dir: Option<&std::path::Path>,
) -> Vec<Element> {
    let meta = extract_document_meta(elements);
    let mut out = tex_to_pdfrs_elements(elements, image_base_dir);
    prepend_document_meta(&mut out, &meta);
    out
}

fn prepend_document_meta(out: &mut Vec<Element>, meta: &DocumentPdfMeta) {
    let mut header = Vec::new();
    if let Some(title) = &meta.title {
        header.push(Element::Heading {
            level: 1,
            text: title.clone(),
        });
    }
    if let Some(author) = &meta.author {
        header.push(Element::Paragraph {
            text: author.clone(),
        });
    }
    if let Some(date) = &meta.date {
        let date_text = if date == "\\today" {
            chrono::Local::now().format("%B %d, %Y").to_string()
        } else {
            date.clone()
        };
        header.push(Element::Paragraph { text: date_text });
    }
    if !header.is_empty() {
        header.push(Element::EmptyLine);
        header.append(out);
        *out = header;
    }
}

/// Options passed to the pdfrs PDF backend.
#[derive(Debug, Clone)]
pub struct PdfRenderOptions {
    pub layout: PdfrsLayout,
    pub font: String,
    pub base_font_size: f32,
    pub image_base_dir: Option<PathBuf>,
    pub accessibility: Option<AccessibilityOptions>,
}

impl Default for PdfRenderOptions {
    fn default() -> Self {
        Self {
            layout: PdfrsLayout::portrait(),
            font: "Helvetica".to_string(),
            base_font_size: 11.0,
            image_base_dir: None,
            accessibility: None,
        }
    }
}

/// Render LaTeX elements to PDF bytes using pdfrs.
pub fn render_pdf_bytes(
    elements: &[TexElement],
    mut options: PdfRenderOptions,
) -> Result<Vec<u8>, LatexError> {
    let meta = extract_document_meta(elements);
    if let Some(title) = meta.title {
        options.accessibility = Some(options.accessibility.unwrap_or_default().with_title(title));
    }
    let pdfrs_elements =
        tex_to_pdfrs_document_with_base(elements, options.image_base_dir.as_deref());
    if pdfrs_elements.len() > PDFRS_MAX_ELEMENTS {
        return Err(LatexError::PdfError {
            message: format!(
                "pdfrs element count {} exceeds limit {PDFRS_MAX_ELEMENTS}",
                pdfrs_elements.len()
            ),
            context: None,
        });
    }
    render_pdfrs_element_bytes(&pdfrs_elements, options)
}

/// Render pre-built pdfrs elements to PDF bytes.
pub fn render_pdfrs_element_bytes(
    elements: &[Element],
    options: PdfRenderOptions,
) -> Result<Vec<u8>, LatexError> {
    let profile = OptimizationProfile::Archive;
    let profile = if let Some(accessibility) = options.accessibility {
        let mut settings = profile.settings();
        settings.tagged_pdf = accessibility.tagged_pdf;
        OptimizationProfile::Custom(settings)
    } else {
        profile
    };
    let mut generator = OptimizedPdfGenerator::new(profile)
        .with_layout(options.layout)
        .with_font(&options.font)
        .with_font_size(options.base_font_size);
    if let Some(base) = options.image_base_dir {
        generator = generator.with_image_base_dir(base);
    }
    generator
        .generate_bytes(elements)
        .map_err(|e| LatexError::PdfError {
            message: e.to_string(),
            context: None,
        })
}

struct ElementWriter {
    out: Vec<Element>,
    segments: Vec<TextSegment>,
}

impl ElementWriter {
    fn new() -> Self {
        Self {
            out: Vec::new(),
            segments: Vec::new(),
        }
    }

    fn finish(mut self) -> Vec<Element> {
        self.flush_rich();
        self.out
    }

    fn flush_rich(&mut self) {
        if self.segments.is_empty() {
            return;
        }
        let segments = merge_plain_segments(std::mem::take(&mut self.segments));
        self.out.push(Element::RichParagraph { segments });
    }

    fn push_plain(&mut self, text: &str) {
        let normalized: String = text.chars().map(|c| if c == '\n' { ' ' } else { c }).collect();
        if normalized.trim().is_empty() {
            return;
        }
        if let Some(TextSegment::Plain(last)) = self.segments.last_mut() {
            if !last.ends_with(' ') && !normalized.starts_with(' ') {
                last.push(' ');
            }
            last.push_str(&normalized);
        } else {
            self.segments.push(TextSegment::Plain(normalized));
        }
    }

    fn push_segment(&mut self, segment: TextSegment) {
        self.segments.push(segment);
    }

    fn empty_line(&mut self) {
        self.flush_rich();
        self.out.push(Element::EmptyLine);
    }

    fn push_block(&mut self, element: Element) {
        self.flush_rich();
        self.out.push(element);
    }
}

fn merge_plain_segments(segments: Vec<TextSegment>) -> Vec<TextSegment> {
    let mut merged = Vec::new();
    for segment in segments {
        match segment {
            TextSegment::Plain(text) => {
                if let Some(TextSegment::Plain(last)) = merged.last_mut() {
                    if !last.ends_with(' ') && !text.starts_with(' ') {
                        last.push(' ');
                    }
                    last.push_str(&text);
                } else {
                    merged.push(TextSegment::Plain(text));
                }
            }
            other => merged.push(other),
        }
    }
    merged
}

fn push_tex_element(
    element: &TexElement,
    writer: &mut ElementWriter,
    list_depth: u8,
    image_base_dir: Option<&std::path::Path>,
) {
    match element {
        TexElement::Text(text) => push_text_with_inline_math(writer, text),
        TexElement::Paragraph => writer.empty_line(),
        TexElement::Section { level, title } => {
            writer.push_block(Element::Heading {
                level: section_heading_level(*level),
                text: title.clone(),
            });
        }
        TexElement::MathInline(expr) => {
            push_inline_math_segment(writer, expr);
        }
        TexElement::MathDisplay(expr) => {
            writer.push_block(Element::MathBlock {
                expression: math_block_expression(expr),
            });
        }
        TexElement::MathLines { lines, kind } => {
            let processed: Vec<String> = lines
                .iter()
                .map(|l| match kind {
                    MathLineKind::Align => l.replace('&', " ").replace("  ", " "),
                    _ => l.replace('&', " "),
                })
                .collect();
            writer.push_block(Element::MathBlock {
                expression: math_block_expression(&processed.join("\n")),
            });
        }
        TexElement::ItemList {
            ordered,
            labels,
            items,
        } => {
            writer.flush_rich();
            for (idx, item) in items.iter().enumerate() {
                let inline: Vec<TexElement> = item
                    .iter()
                    .filter(|el| !matches!(el, TexElement::ItemList { .. }))
                    .cloned()
                    .collect();
                let nested: Vec<&TexElement> = item
                    .iter()
                    .filter(|el| matches!(el, TexElement::ItemList { .. }))
                    .collect();

                let (text, display_math) = split_item_content(&inline);
                if !inline.is_empty() {
                    if *ordered {
                        writer.out.push(Element::OrderedListItem {
                            number: (idx + 1) as u32,
                            text: text.clone(),
                            depth: list_depth,
                        });
                    } else {
                        let label = labels.get(idx).and_then(|l| l.as_ref());
                        let display = if let Some(lbl) = label {
                            if text.is_empty() {
                                lbl.clone()
                            } else {
                                format!("{lbl} {text}")
                            }
                        } else {
                            text
                        };
                        writer.out.push(Element::UnorderedListItem {
                            text: display,
                            depth: list_depth,
                        });
                    }
                }

                for expr in display_math {
                    writer.out.push(Element::MathBlock {
                        expression: math_block_expression(&expr),
                    });
                }

                for nested_list in nested {
                    push_tex_element(nested_list, writer, list_depth + 1, image_base_dir);
                }
            }
        }
        TexElement::DescriptionList { items } => {
            writer.flush_rich();
            for item in items {
                writer.out.push(Element::DefinitionItem {
                    term: item.term.clone(),
                    definition: flatten_item_text(&item.body),
                });
            }
        }
        TexElement::Theorem { kind, title, body } => {
            let mut heading = kind[..1].to_uppercase() + &kind[1..];
            if let Some(t) = title {
                heading.push_str(&format!(" ({t})"));
            }
            writer.push_block(Element::Heading {
                level: 4,
                text: heading,
            });
            push_children(body, writer, list_depth, image_base_dir);
        }
        TexElement::CodeBlock(code) => {
            writer.push_block(Element::CodeBlock {
                language: "latex".to_string(),
                code: code.clone(),
            });
        }
        TexElement::Image { path, .. } => {
            let resolved_path = rasterize_svg_if_needed(path, image_base_dir);
            writer.push_block(Element::Image {
                alt: String::new(),
                path: resolved_path,
            });
        }
        TexElement::Table(table) => {
            writer.flush_rich();
            push_table(table, &mut writer.out);
        }
        TexElement::ColoredText { text, .. } => {
            writer.push_plain(text);
        }
        TexElement::Citation { keys, kind } => {
            let label = match kind.as_str() {
                "nocite" => String::new(),
                "parencite" => format!("({})", keys.join(", ")),
                "footcite" => format!("[{}]", keys.join(", ")),
                _ => format!("[{}]", keys.join(", ")),
            };
            if !label.is_empty() {
                writer.push_plain(&label);
            }
        }
        TexElement::Bibliography { entries } => {
            writer.flush_rich();
            for entry in entries {
                writer.out.push(Element::CitationDef {
                    key: entry.key.clone(),
                    text: entry.text.clone(),
                });
            }
            writer.out.push(Element::Bibliography);
        }
        TexElement::Label { .. } => {}
        TexElement::Ref { key } | TexElement::PageRef { key } => {
            writer.push_plain(&format!("?? ({key})"));
        }
        TexElement::Center(inner) | TexElement::Quote(inner) | TexElement::Abstract(inner) => {
            if matches!(element, TexElement::Abstract(_)) {
                writer.push_block(Element::Heading {
                    level: 3,
                    text: "Abstract".to_string(),
                });
            }
            for child in inner {
                if matches!(child, TexElement::Text(t) if !t.trim().is_empty()) {
                    if let TexElement::Text(t) = child {
                        writer.push_block(Element::BlockQuote {
                            text: t.trim().to_string(),
                            depth: 0,
                        });
                    }
                } else {
                    push_tex_element(child, writer, list_depth, image_base_dir);
                }
            }
        }
        TexElement::LineBreak => {
            writer.push_plain("\n");
        }
        TexElement::FlushLeft(inner) | TexElement::FlushRight(inner) => {
            for child in inner {
                push_tex_element(child, writer, list_depth, image_base_dir);
            }
        }
        TexElement::Footnote { text } => {
            writer.push_block(Element::Footnote {
                label: String::new(),
                text: text.clone(),
            });
        }
        TexElement::Caption { text } => {
            writer.push_plain(text);
        }
        TexElement::TableOfContents => writer.push_block(Element::Toc),
        TexElement::ListOfFigures | TexElement::ListOfTables => {
            writer.push_block(Element::Heading {
                level: 2,
                text: if matches!(element, TexElement::ListOfFigures) {
                    "List of Figures".to_string()
                } else {
                    "List of Tables".to_string()
                },
            });
        }
        TexElement::Command { name, args } => match name.as_str() {
            "maketitle" => push_maketitle(writer),
            "title" | "author" | "date" | "newpage" | "clearpage" | "pagebreak" => {}
            "textbf" if !args.is_empty() => {
                writer.push_segment(TextSegment::Bold(args[0].clone()));
            }
            "textit" | "emph" if !args.is_empty() => {
                writer.push_segment(TextSegment::Italic(args[0].clone()));
            }
            "texttt" if !args.is_empty() => {
                writer.push_segment(TextSegment::Code(args[0].clone()));
            }
            "textcolor" if args.len() >= 2 => {
                writer.push_plain(&args[1]);
            }
            "href" if args.len() >= 2 => {
                writer.push_segment(TextSegment::Link {
                    text: args[1].clone(),
                    url: args[0].clone(),
                });
            }
            "url" if !args.is_empty() => {
                writer.push_segment(TextSegment::Link {
                    text: args[0].clone(),
                    url: args[0].clone(),
                });
            }
            "today" => {
                writer.push_plain(&chrono::Local::now().format("%B %d, %Y").to_string());
            }
            "hrulefill" => {
                writer.push_block(Element::HorizontalRule);
            }
            "hspace" | "hspace*" | "vspace" | "vspace*" | "quad" | "qquad"
            | "footnotemark" | "cline" | "rule" | "linebreak" | "nopagebreak"
            | "samepage" | "enlargethispage" | "raggedright" | "raggedleft"
            | "centering" | "appendix" | "bibliography"
            | "bibliographystyle" | "index" | "glossary" => {}
            "noindent" => {
                writer.flush_rich();
            }
            "enquote" if !args.is_empty() => {
                writer.push_plain(&format!("\u{201c}{}\u{201d}", args[0]));
            }
            "textsc" if !args.is_empty() => {
                writer.push_segment(TextSegment::Italic(args[0].clone()));
            }
            "sout" | "underline" if !args.is_empty() => {
                writer.push_plain(&args[0]);
            }
            "textsuperscript" if !args.is_empty() => {
                writer.push_plain(&format!("^{}", args[0]));
            }
            "textsubscript" if !args.is_empty() => {
                writer.push_plain(&format!("_{}", args[0]));
            }
            "multicolumn" if args.len() >= 3 => {
                writer.push_plain(&args[2]);
            }
            "text" | "ensuremath" | "mbox" | "makebox" | "parbox"
            | "textrm" | "textsf" | "textsl" | "textup" | "textmd"
            | "textnormal" | "fbox" | "overline" | "footnotetext"
            | "phantom" | "vphantom" | "hphantom" if !args.is_empty() => {
                writer.push_plain(&args[0]);
            }
            "SI" if args.len() >= 2 => {
                writer.push_plain(&args[0]);
                writer.push_plain(" ");
                writer.push_plain(&args[1]);
            }
            "SIrange" if args.len() >= 3 => {
                writer.push_plain(&args[0]);
                writer.push_plain("–");
                writer.push_plain(&args[1]);
                writer.push_plain(" ");
                writer.push_plain(&args[2]);
            }
            "si" | "unit" | "num" if !args.is_empty() => {
                writer.push_plain(&args[0]);
            }
            _ => {
                if let Some(text) = args.first() {
                    writer.push_plain(text);
                }
            }
        },
    }
}

fn push_children(
    children: &[TexElement],
    writer: &mut ElementWriter,
    depth: u8,
    image_base_dir: Option<&std::path::Path>,
) {
    for child in children {
        push_tex_element(child, writer, depth, image_base_dir);
    }
}

/// Split plain text that embeds `$...$` into rich inline segments.
fn push_text_with_inline_math(writer: &mut ElementWriter, text: &str) {
    let mut plain = String::new();
    let mut in_math = false;
    let mut math_buf = String::new();

    for ch in text.chars() {
        if ch == '$' {
            if in_math {
                flush_plain_buffer(writer, &mut plain);
                push_inline_math_segment(writer, &math_buf);
                math_buf.clear();
                in_math = false;
            } else {
                flush_plain_buffer(writer, &mut plain);
                in_math = true;
            }
        } else if in_math {
            math_buf.push(ch);
        } else {
            plain.push(ch);
        }
    }

    if in_math {
        plain.push('$');
        plain.push_str(&math_buf);
    }
    flush_plain_buffer(writer, &mut plain);
}

fn flush_plain_buffer(writer: &mut ElementWriter, plain: &mut String) {
    if !plain.trim().is_empty() {
        writer.push_plain(plain);
    }
    plain.clear();
}

/// Push inline math using display layout for fractions, otherwise formatted Unicode.
fn push_inline_math_segment(writer: &mut ElementWriter, expr: &str) {
    let trimmed = expr.trim();
    if trimmed.is_empty() {
        return;
    }
    if inline_uses_display_math(trimmed) {
        writer.push_block(Element::MathBlock {
            expression: math_block_expression(trimmed),
        });
        return;
    }
    writer.push_segment(TextSegment::Plain(format_math_for_text(trimmed)));
}

fn inline_uses_display_math(expr: &str) -> bool {
    expr.contains("\\frac")
        || expr.contains("\\dfrac")
        || expr.contains("\\tfrac")
        || expr.contains("\\sqrt")
}

fn math_block_expression(expr: &str) -> String {
    format_matrix_envs(expr)
}

/// Convert `\begin{pmatrix}…\end{pmatrix}` and friends into multi-line
/// bracketed/parenthesised text so that pdfrs's `emit_display_math` (which
/// splits on newlines) renders each matrix row on its own line.
fn format_matrix_envs(expr: &str) -> String {
    let mut s = expr.to_string();
    for &(env, left, right) in &[
        ("pmatrix", "(", ")"),
        ("bmatrix", "[", "]"),
        ("vmatrix", "|", "|"),
        ("matrix", "", ""),
    ] {
        let open = format!("\\begin{{{}}}", env);
        let close = format!("\\end{{{}}}", env);
        while let Some(start) = s.find(&open) {
            let body_start = start + open.len();
            let Some(rel_end) = s[body_start..].find(&close) else {
                break;
            };
            let body = s[body_start..body_start + rel_end].trim();
            let rows: Vec<String> = body
                .split("\\\\")
                .map(|r| {
                    r.trim()
                        .split('&')
                        .map(str::trim)
                        .filter(|c| !c.is_empty())
                        .collect::<Vec<_>>()
                        .join("  ")
                })
                .filter(|r| !r.is_empty())
                .map(|r| format!("{} {} {}", left, r, right))
                .collect();
            let replacement = rows.join("\n");
            let end = body_start + rel_end + close.len();
            s.replace_range(start..end, &replacement);
        }
    }
    s
}

fn push_maketitle(_writer: &mut ElementWriter) {
    // Title block is usually emitted via preceding \title/\author/\date commands;
    // maketitle itself is a no-op marker in the pdfrs stream.
    _writer.empty_line();
}

fn push_table(table: &Table, out: &mut Vec<Element>) {
    let alignments: Vec<TableAlignment> = table
        .columns
        .iter()
        .map(|a| match a {
            Align::Left => TableAlignment::Left,
            Align::Center => TableAlignment::Center,
            Align::Right => TableAlignment::Right,
        })
        .collect();

    for row in &table.rows {
        if row.is_separator {
            out.push(Element::HorizontalRule);
            continue;
        }
        out.push(Element::TableRow {
            cells: row.cells.clone(),
            is_separator: false,
            alignments: alignments.clone(),
            colspans: Vec::new(),
            rowspans: Vec::new(),
        });
    }
}

fn flatten_item_text(items: &[TexElement]) -> String {
    split_item_content(items).0
}

/// Split list-item content into plain text and display-math expressions.
///
/// `\frac` / `\sqrt` go to display layout (vinculum / stacked fractions);
/// simple symbols stay as Unicode in the list item text.
fn split_item_content(items: &[TexElement]) -> (String, Vec<String>) {
    let mut parts = Vec::new();
    let mut display = Vec::new();

    for item in items {
        match item {
            TexElement::Text(t) => {
                collect_text_with_math(t, &mut parts, &mut display);
            }
            TexElement::MathInline(m) => {
                if inline_uses_display_math(m) {
                    display.push(m.clone());
                } else {
                    parts.push(format_math_for_text(m));
                }
            }
            TexElement::Command { name, args }
                if matches!(name.as_str(), "textbf" | "textit" | "emph" | "texttt") =>
            {
                if let Some(a) = args.first() {
                    parts.push(a.clone());
                }
            }
            TexElement::ColoredText { text, .. } => parts.push(text.clone()),
            _ => {}
        }
    }
    (parts.join(" "), display)
}

fn collect_text_with_math(text: &str, parts: &mut Vec<String>, display: &mut Vec<String>) {
    let mut plain = String::new();
    let mut in_math = false;
    let mut math_buf = String::new();

    for ch in text.chars() {
        if ch == '$' {
            if in_math {
                let trimmed = math_buf.trim().to_string();
                if !trimmed.is_empty() {
                    if inline_uses_display_math(&trimmed) {
                        flush_part(parts, &mut plain);
                        display.push(trimmed);
                    } else {
                        plain.push_str(&format_math_for_text(&trimmed));
                    }
                }
                math_buf.clear();
                in_math = false;
            } else {
                in_math = true;
            }
        } else if in_math {
            math_buf.push(ch);
        } else {
            plain.push(ch);
        }
    }
    if in_math {
        plain.push('$');
        plain.push_str(&math_buf);
    }
    flush_part(parts, &mut plain);
}

fn flush_part(parts: &mut Vec<String>, plain: &mut String) {
    let trimmed = plain.trim();
    if !trimmed.is_empty() {
        parts.push(trimmed.to_string());
    }
    plain.clear();
}

fn section_heading_level(level: usize) -> u8 {
    match level {
        0 => 1,
        1 => 1,
        2 => 2,
        3 => 3,
        4 => 4,
        5 => 5,
        _ => 6,
    }
}

/// Format inline math for plain-text contexts (list items, etc.).
fn format_math_for_text(expr: &str) -> String {
    crate::math_formatter::MathFormatter::format(expr)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Plain text of a paragraph-like element (justified, rich, or plain).
    fn paragraph_text(elem: &Element) -> Option<String> {
        match elem {
            Element::Paragraph { text } => Some(text.clone()),
            Element::RichParagraph { segments } => {
                let mut text = String::new();
                for seg in segments {
                    match seg {
                        TextSegment::Plain(t) => text.push_str(t),
                        TextSegment::Bold(t)
                        | TextSegment::Italic(t)
                        | TextSegment::BoldItalic(t)
                        | TextSegment::Code(t)
                        | TextSegment::Strikethrough(t) => text.push_str(t),
                        TextSegment::MathInline(expr) => text.push_str(expr),
                        TextSegment::Link { text: t, url } => {
                            text.push_str(t);
                            text.push_str(&format!(" ({url})"));
                        }
                        TextSegment::Citation { key } => text.push_str(key),
                    }
                }
                Some(text)
            }
            _ => None,
        }
    }

    #[test]
    fn maps_section_to_heading() {
        let elements = vec![TexElement::Section {
            level: 1,
            title: "Intro".to_string(),
        }];
        let mapped = tex_to_pdfrs_elements(&elements, None);
        assert!(matches!(
            mapped.first(),
            Some(Element::Heading { level: 1, text }) if text == "Intro"
        ));
    }

    #[test]
    fn coalesces_consecutive_text_into_one_paragraph() {
        let elements = vec![
            TexElement::Text("Hello".to_string()),
            TexElement::Text("world".to_string()),
            TexElement::Paragraph,
            TexElement::Text("Next".to_string()),
            TexElement::Text("line".to_string()),
        ];
        let mapped = tex_to_pdfrs_elements(&elements, None);
        assert_eq!(mapped.len(), 3);
        assert_eq!(
            paragraph_text(&mapped[0]).as_deref(),
            Some("Hello world"),
            "consecutive text coalesces into one justified paragraph"
        );
        assert!(matches!(mapped[1], Element::EmptyLine));
        assert_eq!(paragraph_text(&mapped[2]).as_deref(), Some("Next line"));
    }

    #[test]
    fn renders_nested_lists_with_pdfrs() {
        let content = std::fs::read_to_string("examples/lists.tex").expect("lists.tex");
        let mut parser = crate::TexParser::new(content);
        let elements = parser.parse();
        let pdf = render_pdf_bytes(&elements, PdfRenderOptions::default()).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        assert!(
            pdf.len() < 100_000,
            "lists.tex should render via pdfrs (<100KB), got {} bytes",
            pdf.len()
        );
    }

    #[test]
    fn prepends_document_metadata() {
        let elements = vec![
            TexElement::Command {
                name: "title".to_string(),
                args: vec!["My Doc".to_string()],
            },
            TexElement::Command {
                name: "author".to_string(),
                args: vec!["Alice".to_string()],
            },
            TexElement::Text("Body".to_string()),
        ];
        let mapped = tex_to_pdfrs_document(&elements);
        assert!(matches!(
            mapped.first(),
            Some(Element::Heading { level: 1, text }) if text == "My Doc"
        ));
        assert!(mapped.iter().any(|e| paragraph_text(e).as_deref() == Some("Alice")));
    }

    #[test]
    fn renders_minimal_document_to_pdf() {
        let elements = vec![
            TexElement::Command {
                name: "title".to_string(),
                args: vec!["Test".to_string()],
            },
            TexElement::Text("Hello world".to_string()),
        ];
        let pdf = render_pdf_bytes(&elements, PdfRenderOptions::default()).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
    }

    #[test]
    fn math_example_renders_via_pdfrs() {
        let content = std::fs::read_to_string("examples/math.tex").expect("math.tex");
        let mut parser = crate::TexParser::new(content);
        let elements = parser.parse();
        let pdf = render_pdf_bytes(&elements, PdfRenderOptions::default()).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        assert!(
            pdf.len() < 500_000,
            "math.tex should use pdfrs (<500KB), got {} bytes",
            pdf.len()
        );
    }

    #[test]
    fn simple_test_embedded_math_renders_without_dollar_delimiters() {
        let content = std::fs::read_to_string("examples/simple_test.tex").expect("simple_test.tex");
        let mut parser = crate::TexParser::new(content);
        let elements = parser.parse();
        let mapped = tex_to_pdfrs_document(&elements);
        let has_rendered_math = mapped.iter().any(|e| {
            paragraph_text(e).is_some_and(|t| t.contains('α') || t.contains('∑'))
        });
        assert!(
            has_rendered_math,
            "expected rendered inline math, got: {mapped:?}"
        );
        assert!(
            !mapped.iter().any(|e| {
                paragraph_text(e).is_some_and(|t| t.contains('$'))
            }),
            "literal $ delimiters should not appear in output"
        );
    }

    #[test]
    fn advanced_math_example_renders_greek_symbols() {
        let content =
            std::fs::read_to_string("examples/advanced_math.tex").expect("advanced_math.tex");
        let mut parser = crate::TexParser::new(content);
        let elements = parser.parse();
        let pdf = render_pdf_bytes(&elements, PdfRenderOptions::default()).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        assert!(
            pdf.len() < 200_000,
            "advanced_math PDF should be reasonable, got {} bytes",
            pdf.len()
        );
        let mapped = tex_to_pdfrs_document(&elements);
        assert!(
            mapped
                .iter()
                .any(|e| paragraph_text(e).is_some_and(|t| t.contains('α') || t.contains('β'))),
            "expected rendered Greek letters in mapped output"
        );
    }

    #[test]
    fn features_example_renders_with_pdfrs() {
        let content = std::fs::read_to_string("examples/features.tex").expect("features.tex");
        let mut parser = crate::TexParser::new(content);
        let elements = parser.parse();
        let mapped = tex_to_pdfrs_document(&elements);
        assert!(
            mapped
                .iter()
                .any(|e| matches!(e, Element::DefinitionItem { .. })),
            "expected description list items"
        );
        assert!(
            mapped
                .iter()
                .any(|e| matches!(e, Element::MathBlock { .. })),
            "expected display math blocks"
        );
        assert!(
            mapped
                .iter()
                .any(|e| matches!(
                    e,
                    Element::RichParagraph { .. }
                )),
            "expected inline rich/justified paragraphs for texttt/href"
        );
        let pdf = render_pdf_bytes(&elements, PdfRenderOptions::default()).unwrap();
        assert!(pdf.starts_with(b"%PDF"));
        assert!(
            pdf.len() < 200_000,
            "features.tex PDF should be reasonable size, got {} bytes",
            pdf.len()
        );
    }

    #[test]
    fn inline_formatting_uses_rich_paragraph() {
        let elements = vec![
            TexElement::Text("Use ".to_string()),
            TexElement::Command {
                name: "texttt".to_string(),
                args: vec!["align".to_string()],
            },
            TexElement::Text(" for equations.".to_string()),
        ];
        let mapped = tex_to_pdfrs_elements(&elements, None);
        assert!(matches!(
            mapped.first(),
            Some(Element::RichParagraph { segments })
            if segments.len() >= 3
        ));
    }

    #[test]
    fn unicode_math_pdf_stays_small_with_subset_fonts() {
        use pdfrs::elements::Element;
        let formatted = crate::math_formatter::MathFormatter::format(
            "x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}",
        );
        let elements = vec![Element::Paragraph { text: formatted }];
        let pdf = render_pdfrs_element_bytes(&elements, PdfRenderOptions::default()).unwrap();
        assert!(
            pdf.len() < 500_000,
            "subset Unicode PDF should be <500KB, got {} bytes",
            pdf.len()
        );
    }

    #[test]
    fn display_math_paragraph_stays_small() {
        let elements = vec![TexElement::MathDisplay(
            "x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}".to_string(),
        )];
        let pdf = render_pdf_bytes(&elements, PdfRenderOptions::default()).unwrap();
        assert!(pdf.len() < 500_000, "got {} bytes", pdf.len());
    }

    #[test]
    fn list_item_sqrt_emits_math_block() {
        let elements = vec![TexElement::ItemList {
            ordered: false,
            labels: vec![],
            items: vec![vec![TexElement::Text("Root $\\sqrt{x^2+y^2}$".to_string())]],
        }];
        let mapped = tex_to_pdfrs_elements(&elements, None);
        assert!(
            mapped.iter().any(|e| matches!(
                e,
                Element::MathBlock { expression } if expression.contains("\\sqrt")
            )),
            "expected MathBlock with raw \\sqrt for pdfrs vinculum rendering, got: {mapped:?}"
        );
    }

    #[test]
    fn renders_math_inline() {
        let elements = vec![
            TexElement::Text("Angle ".to_string()),
            TexElement::MathInline("\\alpha".to_string()),
        ];
        let mapped = tex_to_pdfrs_elements(&elements, None);
        assert_eq!(
            paragraph_text(mapped.first().unwrap()).as_deref(),
            Some("Angle α"),
            "inline math renders as Unicode inside a justified paragraph"
        );
    }

    #[test]
    fn sqrt_in_expression_uses_math_block_with_vinculum() {
        let elements = vec![TexElement::Text(
            "Square root: $\\sqrt{x^2 + y^2}$".to_string(),
        )];
        let mapped = tex_to_pdfrs_elements(&elements, None);
        assert!(
            mapped.iter().any(|e| matches!(
                e,
                Element::MathBlock { expression } if expression.contains("\\sqrt")
            )),
            "expected MathBlock with raw \\sqrt for pdfrs vinculum rendering, got: {mapped:?}"
        );
    }

    #[test]
    fn frac_in_inline_math_uses_math_block() {
        let elements = vec![TexElement::Text("Formula: $x = \\frac{1}{2}$".to_string())];
        let mapped = tex_to_pdfrs_elements(&elements, None);
        assert!(
            mapped
                .iter()
                .any(|e| matches!(e, Element::MathBlock { .. })),
            "expected display math block for inline fraction, got: {mapped:?}"
        );
    }

    #[test]
    fn math_lines_join_with_newlines_not_backslashes() {
        use crate::parser::MathLineKind;
        let elements = vec![TexElement::MathLines {
            lines: vec!["a = b + c".to_string(), "d = e".to_string()],
            kind: MathLineKind::Align,
        }];
        let mapped = tex_to_pdfrs_elements(&elements, None);
        let block = mapped.iter().find(|e| matches!(e, Element::MathBlock { .. }));
        assert!(block.is_some(), "expected MathBlock for MathLines");
        if let Some(Element::MathBlock { expression }) = block {
            assert!(
                expression.contains('\n'),
                "expected newline-separated lines, got: {expression:?}"
            );
            assert!(
                !expression.contains("\\\\"),
                "expected no literal backslash-backslash, got: {expression:?}"
            );
        }
    }

    #[test]
    fn math_lines_align_strips_ampersands() {
        use crate::parser::MathLineKind;
        let elements = vec![TexElement::MathLines {
            lines: vec!["a & = b".to_string()],
            kind: MathLineKind::Align,
        }];
        let mapped = tex_to_pdfrs_elements(&elements, None);
        if let Some(Element::MathBlock { expression }) =
            mapped.iter().find(|e| matches!(e, Element::MathBlock { .. }))
        {
            assert!(
                !expression.contains('&'),
                "expected & stripped for Align, got: {expression:?}"
            );
        }
    }

    #[test]
    fn pmatrix_renders_as_multiline_with_parens() {
        let elements = vec![TexElement::MathDisplay(
            "\\begin{pmatrix} a & b \\\\ c & d \\end{pmatrix}".to_string(),
        )];
        let mapped = tex_to_pdfrs_elements(&elements, None);
        let block = mapped.iter().find(|e| matches!(e, Element::MathBlock { .. }));
        assert!(block.is_some(), "expected MathBlock for pmatrix");
        if let Some(Element::MathBlock { expression }) = block {
            assert!(
                expression.contains("( a  b )"),
                "expected first row with parens, got: {expression:?}"
            );
            assert!(
                expression.contains("( c  d )"),
                "expected second row with parens, got: {expression:?}"
            );
            assert!(
                !expression.contains("\\begin{pmatrix}"),
                "expected no raw begin pmatrix, got: {expression:?}"
            );
        }
    }

    #[test]
    fn sqrt_passes_raw_to_pdfrs_for_vinculum() {
        let elements = vec![TexElement::MathDisplay(
            "\\sqrt{b^2 - 4ac}".to_string(),
        )];
        let mapped = tex_to_pdfrs_elements(&elements, None);
        if let Some(Element::MathBlock { expression }) =
            mapped.iter().find(|e| matches!(e, Element::MathBlock { .. }))
        {
            assert!(
                expression.contains("\\sqrt"),
                "expected raw \\sqrt for pdfrs vinculum rendering, got: {expression:?}"
            );
        }
    }
}