Skip to main content

docling_core/
typst.rs

1//! Typst serializer (#1226) — `--to typst`: the document body as Typst
2//! markup (`.typ`), for a pure-Rust / WASM `document → Typst → PDF` chain
3//! without Pandoc. docling has no Typst serializer, so there is no upstream
4//! output to match; the walk follows the LaTeX serializer's ([`crate::latex`])
5//! reading of the model — body layer only, a level-1 heading is the title,
6//! runs of list items fold into (nested) lists, rich table cells render their
7//! blocks — and the Markdown inline markers baked into the node text
8//! (`**bold**`, `*italic*`, `~~strike~~`, `` `code` ``, `[text](url)`,
9//! `$formula$`) become `#strong[…]` / `#emph[…]` / `#strike[…]` / `#raw(…)` /
10//! `#link(…)[…]` / math.
11//!
12//! The output is body markup only: no `#set` rules, no template, no
13//! preamble, so a caller wraps it in its own (`#import "template.typ": *`
14//! then `#include "doc.typ"`). The crate gains no dependency — the Typst
15//! compiler is the caller's.
16//!
17//! Mapping:
18//! - headings → `=` × level (docling's title is the level-1 heading);
19//! - paragraphs → escaped markup (every character Typst markup would read
20//!   as syntax is backslash-escaped, line-start markers only at a line
21//!   start), an in-text line break → Typst's `\` line break;
22//! - lists → `-` / `+` items, nesting by two-space indentation; a checkbox
23//!   item is a bullet with `☐` / `☒`;
24//! - code → a fenced raw block with its language (a fence longer than any
25//!   backtick run inside); inline code → `#raw("…")`;
26//! - tables → `#table(columns: N, …)`, header rows as `table.header(…)`,
27//!   spans as `table.cell(colspan: c, rowspan: r)[…]`, wrapped in
28//!   `#figure(…, caption: […])` when captioned, footnotes after it;
29//! - pictures → `#image("…")` under [`ImageMode::Referenced`] (the files
30//!   are returned like the Markdown export's `artifacts/image_NNNNNN.<ext>`),
31//!   in a `#figure` with its caption; otherwise — and for an encoding Typst
32//!   cannot decode (EMF, TIFF, BMP) — a `/* image */` placeholder, a caption
33//!   still making it a figure. Typst has no way to decode a `data:` URI, so
34//!   [`ImageMode::Embedded`] falls back to the placeholder too;
35//! - formulas → Typst math when the LaTeX source only uses the constructs
36//!   [`latex_to_typst_math`] translates (scripts, `\frac`, `\sqrt`, Greek,
37//!   operators, relations, arrows, `\mathbf` & co., `\left…\right`), else
38//!   the LaTeX as a `latex` raw block / inline raw — never a guess that
39//!   might not compile.
40
41use crate::document::{DoclingDocument, FieldItem, Node, Table};
42use crate::markdown::ImageMode;
43
44/// Options for [`DoclingDocument::export_to_typst_with`].
45#[derive(Debug, Clone)]
46pub struct TypstExportOptions {
47    /// How pictures carry their image: [`ImageMode::Referenced`] writes
48    /// `#image("<artifacts_dir>/image_NNNNNN.<ext>")` and returns the
49    /// files; any other mode is the placeholder (see the module docs).
50    pub image_mode: ImageMode,
51    /// The directory referenced images are named under.
52    pub artifacts_dir: String,
53}
54
55impl Default for TypstExportOptions {
56    fn default() -> Self {
57        Self {
58            image_mode: ImageMode::Placeholder,
59            artifacts_dir: "artifacts".to_string(),
60        }
61    }
62}
63
64/// The Typst markup and, for [`ImageMode::Referenced`], the
65/// `(path, bytes)` image files it links to.
66pub type TypstOutput = (String, Vec<(String, Vec<u8>)>);
67
68const IMAGE_PLACEHOLDER: &str = "/* image */";
69
70struct Ctx {
71    referenced: bool,
72    artifacts_dir: String,
73    pic_index: usize,
74    artifacts: Vec<(String, Vec<u8>)>,
75}
76
77/// Serialize `doc` as Typst body markup, ending in one newline (an empty
78/// document is the empty string).
79pub fn to_typst(doc: &DoclingDocument, options: &TypstExportOptions) -> TypstOutput {
80    let mut ctx = Ctx {
81        referenced: options.image_mode == ImageMode::Referenced,
82        artifacts_dir: options.artifacts_dir.trim_end_matches('/').to_string(),
83        pic_index: 0,
84        artifacts: Vec::new(),
85    };
86    let body = render_nodes(&mut ctx, &doc.nodes, 0).join("\n\n");
87    let body = if body.is_empty() {
88        body
89    } else {
90        format!("{body}\n")
91    };
92    (body, ctx.artifacts)
93}
94
95// ---------------------------------------------------------------------------
96// Escaping
97// ---------------------------------------------------------------------------
98
99/// Escape `text` as Typst markup text. `line_start`: the text begins a
100/// markup line, where `=`, `-`, `+`, `/` and `1.` open a heading / list /
101/// term / enumeration. A newline becomes a Typst line break (`\` at the end
102/// of the line) and the next line is escaped as a line start; a run of
103/// newlines is one break (a blank line would end the paragraph).
104pub fn escape_typst(text: &str, line_start: bool) -> String {
105    let chars: Vec<char> = text.chars().collect();
106    let mut out = String::with_capacity(text.len() + 8);
107    let mut at_start = line_start;
108    let mut i = 0;
109    while i < chars.len() {
110        let c = chars[i];
111        if c == '\r' {
112            i += 1;
113            continue;
114        }
115        if c == '\n' {
116            while i < chars.len() && (chars[i] == '\n' || chars[i] == '\r') {
117                i += 1;
118            }
119            // A trailing break carries nothing.
120            if i < chars.len() {
121                // Drop the spaces before the break: `\` must end the line.
122                while out.ends_with(' ') || out.ends_with('\t') {
123                    out.pop();
124                }
125                out.push_str(" \\\n");
126                at_start = true;
127                while i < chars.len() && (chars[i] == ' ' || chars[i] == '\t') {
128                    i += 1;
129                }
130            }
131            continue;
132        }
133        if at_start {
134            if c == ' ' || c == '\t' {
135                i += 1;
136                continue;
137            }
138            at_start = false;
139            if matches!(c, '=' | '-' | '+' | '/') {
140                out.push('\\');
141                out.push(c);
142                i += 1;
143                continue;
144            }
145            if c.is_ascii_digit() {
146                // `12.` opens an enumeration item: escape its dot.
147                let mut j = i;
148                while j < chars.len() && chars[j].is_ascii_digit() {
149                    j += 1;
150                }
151                out.extend(&chars[i..j]);
152                if chars.get(j) == Some(&'.') {
153                    out.push_str("\\.");
154                    j += 1;
155                }
156                i = j;
157                continue;
158            }
159        }
160        match c {
161            '\\' | '#' | '$' | '*' | '_' | '`' | '<' | '>' | '@' | '[' | ']' | '~' => {
162                out.push('\\');
163                out.push(c);
164            }
165            // `//` and `/*` open comments.
166            '/' if matches!(chars.get(i + 1), Some('/' | '*')) => out.push_str("\\/"),
167            // `--` / `---` are dash shorthands, `-?` a soft hyphen.
168            '-' if matches!(chars.get(i + 1), Some('-' | '?')) => out.push_str("\\-"),
169            c => out.push(c),
170        }
171        i += 1;
172    }
173    out
174}
175
176/// A Typst string literal (`"…"`, with `\\`, `\"` and control escapes).
177fn string_lit(s: &str) -> String {
178    let mut out = String::with_capacity(s.len() + 2);
179    out.push('"');
180    for c in s.chars() {
181        match c {
182            '\\' => out.push_str("\\\\"),
183            '"' => out.push_str("\\\""),
184            '\n' => out.push_str("\\n"),
185            '\r' => out.push_str("\\r"),
186            '\t' => out.push_str("\\t"),
187            c if c.is_control() => out.push_str(&format!("\\u{{{:x}}}", c as u32)),
188            c => out.push(c),
189        }
190    }
191    out.push('"');
192    out
193}
194
195/// The JSON export's `unescape_text`: the model text minus the Markdown
196/// escapes docling's serializer added.
197fn unescape_text(s: &str) -> String {
198    s.replace("&lt;", "<")
199        .replace("&gt;", ">")
200        .replace("&amp;", "&")
201        .replace("\\_", "_")
202}
203
204// ---------------------------------------------------------------------------
205// Inline markup — Markdown markers into Typst (module docs).
206// ---------------------------------------------------------------------------
207
208/// Render a text carrying docling's Markdown inline markers as Typst inline
209/// markup, starting at a line start.
210fn inline_md(md: &str) -> String {
211    let chars: Vec<char> = crate::markdown::strip_hard_breaks(md).chars().collect();
212    let mut w = Inline::new(true);
213    render_inline(&chars, true, &mut w);
214    w.finish()
215}
216
217/// [`inline_md`] for a table cell: a `$…$` in a plain cell stays text (as
218/// in the LaTeX export), and newlines flatten to spaces.
219fn inline_cell(md: &str) -> String {
220    let flat = crate::markdown::strip_hard_breaks(md).replace('\n', " ");
221    let chars: Vec<char> = flat.chars().collect();
222    let mut w = Inline::new(true);
223    render_inline(&chars, false, &mut w);
224    w.finish()
225}
226
227/// The inline writer: plain runs are buffered and escaped on flush; after an
228/// embedded `#call(…)` a following `.` or `(` would continue the expression
229/// (a method call, another call), so a `;` ends it first.
230struct Inline {
231    out: String,
232    plain: String,
233    line_start: bool,
234    after_code: bool,
235}
236
237impl Inline {
238    fn new(line_start: bool) -> Self {
239        Self {
240            out: String::new(),
241            plain: String::new(),
242            line_start,
243            after_code: false,
244        }
245    }
246
247    fn flush(&mut self) {
248        if self.plain.is_empty() {
249            return;
250        }
251        let raw = unescape_text(&std::mem::take(&mut self.plain));
252        let start = self.line_start && self.out.is_empty();
253        let escaped = escape_typst(&raw, start);
254        if self.after_code && continues_expr(&escaped) {
255            self.out.push(';');
256        }
257        self.after_code = false;
258        self.out.push_str(&escaped);
259    }
260
261    fn code(&mut self, s: &str) {
262        self.flush();
263        if self.after_code && continues_expr(s) {
264            self.out.push(';');
265        }
266        self.out.push_str(s);
267        self.after_code = s.starts_with('#');
268    }
269
270    fn finish(mut self) -> String {
271        self.flush();
272        self.out
273    }
274}
275
276/// Whether `next`, written right after an embedded expression, would extend
277/// it: a call (`(`, `[`) or a field access (`.` and an identifier).
278fn continues_expr(next: &str) -> bool {
279    let mut it = next.chars();
280    match it.next() {
281        Some('(' | '[') => true,
282        Some('.') => it.next().is_some_and(|c| c.is_alphabetic() || c == '_'),
283        _ => false,
284    }
285}
286
287fn starts_with(chars: &[char], at: usize, pat: &str) -> bool {
288    let mut it = chars[at..].iter();
289    pat.chars().all(|p| it.next() == Some(&p))
290}
291
292fn find(chars: &[char], from: usize, pat: &str) -> Option<usize> {
293    let plen = pat.chars().count();
294    (from..chars.len().saturating_sub(plen - 1)).find(|&i| starts_with(chars, i, pat))
295}
296
297fn render_inline(chars: &[char], formulas: bool, w: &mut Inline) {
298    let n = chars.len();
299    let mut i = 0;
300    while i < n {
301        if chars[i] == '[' && !starts_with(chars, i, "[](") && !(i > 0 && chars[i - 1] == '!') {
302            if let Some((label_end, url_end)) = link_bounds(chars, i) {
303                let url: String = chars[label_end + 2..url_end].iter().collect();
304                let link = hyperlink(&chars[i + 1..label_end], &url, formulas);
305                w.code(&link);
306                i = url_end + 1;
307                continue;
308            }
309        }
310        if chars[i] == '`' {
311            if let Some((s, e, after)) = crate::markdown::code_span_bounds(chars, i) {
312                let inner = &chars[s..e];
313                if !inner.is_empty() && !inner.iter().all(|c| c.is_whitespace()) {
314                    let raw: String = inner.iter().collect();
315                    let raw = unescape_text(&raw);
316                    // A fence flattened into the text (a rich cell's block
317                    // code) is block raw; a span inline raw.
318                    let fenced = after - e >= 3;
319                    let raw = if fenced { raw.trim().to_string() } else { raw };
320                    let call = if fenced {
321                        format!("#raw({}, block: true)", string_lit(&raw))
322                    } else {
323                        format!("#raw({})", string_lit(&raw))
324                    };
325                    w.code(&call);
326                    i = after;
327                    continue;
328                }
329            }
330        }
331        let mut matched = false;
332        for marker in ["***", "**", "*", "~~"] {
333            if starts_with(chars, i, marker) {
334                let mlen = marker.chars().count();
335                if let Some(end) = find(chars, i + mlen, marker) {
336                    let inner = &chars[i + mlen..end];
337                    if !inner.is_empty() && !inner.iter().all(|c| c.is_whitespace()) {
338                        let mut sub = Inline::new(true);
339                        render_inline(inner, formulas, &mut sub);
340                        let content = sub.finish();
341                        let call = match marker {
342                            "***" => format!("#strong[#emph[{content}]]"),
343                            "**" => format!("#strong[{content}]"),
344                            "*" => format!("#emph[{content}]"),
345                            _ => format!("#strike[{content}]"),
346                        };
347                        w.code(&call);
348                        i = end + mlen;
349                        matched = true;
350                    }
351                }
352                break;
353            }
354        }
355        if matched {
356            continue;
357        }
358        if formulas && starts_with(chars, i, "$$") {
359            w.plain.push_str("$$");
360            i += 2;
361            continue;
362        }
363        // An inline formula, told from currency by Pandoc's
364        // `tex_math_dollars` rule (as the LaTeX export does).
365        if formulas && chars[i] == '$' {
366            if let Some(end) = find(chars, i + 1, "$") {
367                let non_space = |k: usize| chars.get(k).is_some_and(|c| !c.is_whitespace());
368                let digit_after = chars.get(end + 1).is_some_and(|c| c.is_ascii_digit());
369                if end > i + 1 && non_space(i + 1) && non_space(end - 1) && !digit_after {
370                    let latex: String = chars[i + 1..end].iter().collect();
371                    w.code(&formula(&latex, false));
372                    i = end + 1;
373                    continue;
374                }
375            }
376        }
377        w.plain.push(chars[i]);
378        i += 1;
379    }
380}
381
382/// For a `[` at `open`: the index of the `](` closing the label and of the
383/// `)` closing the URL (balanced brackets / parentheses inside).
384fn link_bounds(chars: &[char], open: usize) -> Option<(usize, usize)> {
385    let mut depth = 0i32;
386    let mut label_end = None;
387    for k in open + 1..chars.len() {
388        match chars[k] {
389            '[' => depth += 1,
390            ']' if depth > 0 => depth -= 1,
391            ']' if starts_with(chars, k, "](") => {
392                label_end = Some(k);
393                break;
394            }
395            ']' => return None,
396            _ => {}
397        }
398    }
399    let label_end = label_end?;
400    let mut depth = 0usize;
401    for (k, &c) in chars.iter().enumerate().skip(label_end + 2) {
402        match c {
403            '(' => depth += 1,
404            ')' if depth == 0 => return Some((label_end, k)),
405            ')' => depth -= 1,
406            _ => {}
407        }
408    }
409    None
410}
411
412/// `#link("url")[label]`; an unsafe destination (`javascript:`, #860)
413/// keeps the label alone.
414fn hyperlink(label: &[char], url: &str, formulas: bool) -> String {
415    let mut sub = Inline::new(true);
416    render_inline(label, formulas, &mut sub);
417    let content = sub.finish();
418    let url = unescape_text(url);
419    if !crate::hyperlink::is_safe_hyperlink(&url) {
420        return content;
421    }
422    if content.is_empty() {
423        format!("#link({})", string_lit(&url))
424    } else {
425        format!("#link({})[{content}]", string_lit(&url))
426    }
427}
428
429/// A formula: Typst math when [`latex_to_typst_math`] can translate the
430/// LaTeX, else the LaTeX source as raw text tagged `latex`.
431fn formula(latex: &str, block: bool) -> String {
432    let latex = latex.trim();
433    match latex_to_typst_math(latex) {
434        Some(math) if block => format!("$ {math} $"),
435        Some(math) => format!("${math}$"),
436        None if block => crate::markdown::code_fence("latex", latex),
437        None => format!("#raw({}, lang: \"latex\")", string_lit(latex)),
438    }
439}
440
441// ---------------------------------------------------------------------------
442// Blocks
443// ---------------------------------------------------------------------------
444
445/// The non-empty Typst blocks of a sibling run, list runs folded into
446/// lists. `indent`: the list nesting the run sits in (0 at the body).
447fn render_nodes(ctx: &mut Ctx, nodes: &[Node], indent: usize) -> Vec<String> {
448    let mut parts = Vec::new();
449    let mut i = 0;
450    while i < nodes.len() {
451        if matches!(nodes[i], Node::ListItem { .. }) {
452            let start = i;
453            i += 1;
454            loop {
455                match nodes.get(i) {
456                    Some(Node::ListItem { .. }) => i += 1,
457                    Some(Node::Paragraph { text })
458                        if text.is_empty()
459                            && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
460                    {
461                        i += 1
462                    }
463                    _ => break,
464                }
465            }
466            for group in sibling_lists(&nodes[start..i]) {
467                let text = render_list(group, indent);
468                if !text.is_empty() {
469                    parts.push(text);
470                }
471            }
472        } else {
473            render_one(ctx, &nodes[i], indent, &mut parts);
474            i += 1;
475        }
476    }
477    parts
478}
479
480fn render_one(ctx: &mut Ctx, node: &Node, indent: usize, parts: &mut Vec<String>) {
481    let push = |parts: &mut Vec<String>, s: String| {
482        if !s.trim().is_empty() {
483            parts.push(s);
484        }
485    };
486    match node {
487        Node::Heading { level, text } => {
488            let body = inline_md(&text.replace('\n', " "));
489            if !body.trim().is_empty() {
490                let marks = "=".repeat(usize::from((*level).max(1)));
491                parts.push(format!("{marks} {body}"));
492            }
493        }
494        Node::Caption { text, .. } => push(parts, inline_md(text)),
495        Node::LabeledText { .. } => render_one(ctx, &node.labeled_as_paragraph(), indent, parts),
496        Node::Paragraph { text } | Node::ListText { text, .. } => {
497            let t = text.trim();
498            match t.strip_prefix("$$").and_then(|s| s.strip_suffix("$$")) {
499                Some(inner) if !inner.trim().is_empty() => push(parts, formula(inner, true)),
500                _ => push(parts, inline_md(text)),
501            }
502        }
503        Node::CheckboxItem { checked, text } => {
504            let mark = if *checked { "☒" } else { "☐" };
505            push(parts, format!("- {mark} {}", inline_md(text)));
506        }
507        Node::Code { language, text, .. } => {
508            let raw = unescape_text(text);
509            let lang = language.as_deref().map(raw_lang).unwrap_or_default();
510            push(parts, crate::markdown::code_fence(&lang, &raw));
511        }
512        Node::Formula { latex, orig, .. } => {
513            if !latex.trim().is_empty() {
514                push(parts, formula(latex, true));
515            } else if !orig.trim().is_empty() {
516                push(parts, "/* formula-not-decoded */".to_string());
517            }
518        }
519        Node::Table(t) => push(parts, render_table(ctx, t)),
520        Node::Picture {
521            caption,
522            image,
523            description,
524            ..
525        } => {
526            let alt = description
527                .as_ref()
528                .filter(|d| d.is_alt_text())
529                .map(|d| d.text.as_str());
530            let img = picture_body(ctx, image.as_ref(), alt);
531            push(parts, figure(img, caption.as_deref()));
532        }
533        Node::Chart { table, caption, .. } => {
534            push(parts, figure(None, caption.as_deref()));
535            push(parts, render_table(ctx, table));
536        }
537        Node::Group { layer: Some(_), .. } => {}
538        Node::Group {
539            label, children, ..
540        } => {
541            if label == "inline" {
542                push(parts, render_nodes(ctx, children, indent).join(" "));
543            } else {
544                push(parts, render_nodes(ctx, children, indent).join("\n\n"));
545            }
546        }
547        Node::FieldRegion { items } => render_field_region(items, parts),
548        Node::KeyValueGraph { .. } => {}
549        Node::InlineGroup { md_text, .. } => push(parts, inline_md(md_text)),
550        Node::TextDump(text) => push(parts, escape_typst(&unescape_text(text), true)),
551        Node::CommentSection { .. } => {}
552        Node::Commented { inner, .. } | Node::ScriptText { inner, .. } => {
553            render_one(ctx, inner, indent, parts)
554        }
555        Node::Located { inner, .. } | Node::Prov { inner, .. } | Node::Track { inner, .. } => {
556            render_one(ctx, inner, indent, parts)
557        }
558        Node::ListItem { .. } => {
559            let text = render_list(std::slice::from_ref(node), indent);
560            push(parts, text);
561        }
562        Node::DoclangOnly(_)
563        | Node::Furniture { .. }
564        | Node::PageFurniture { .. }
565        | Node::FurnitureText { .. }
566        | Node::PictureChildren(_)
567        | Node::PageBreak
568        | Node::PageInfo { .. }
569        | Node::ProvContinuation { .. }
570        | Node::Anchor { .. } => {}
571    }
572}
573
574/// A raw block's language tag: Typst reads it up to the first whitespace or
575/// backtick, so keep a tag of `[A-Za-z0-9_+#.-]` only (docling's `C++`,
576/// `C#`, `objective-c`), lower-cased; anything else is no tag.
577fn raw_lang(lang: &str) -> String {
578    let lang = lang.trim();
579    if !lang.is_empty()
580        && lang
581            .chars()
582            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '+' | '#' | '.' | '-'))
583    {
584        lang.to_ascii_lowercase()
585    } else {
586        String::new()
587    }
588}
589
590/// Field regions: the marker / key / value texts as paragraphs.
591fn render_field_region(items: &[FieldItem], parts: &mut Vec<String>) {
592    for item in items {
593        for text in [&item.marker, &item.key, &item.value].into_iter().flatten() {
594            let t = escape_typst(&unescape_text(text), true);
595            if !t.trim().is_empty() {
596                parts.push(t);
597            }
598        }
599    }
600}
601
602/// The encodings Typst's `image` decodes.
603fn typst_decodes(mimetype: &str) -> bool {
604    matches!(
605        mimetype,
606        "image/png" | "image/jpeg" | "image/gif" | "image/svg+xml" | "image/webp"
607    )
608}
609
610/// A picture's `image(…)` call (code form, no `#`) under referenced
611/// images, registering its file; `None` for the placeholder.
612fn picture_body(
613    ctx: &mut Ctx,
614    image: Option<&crate::document::PictureImage>,
615    alt: Option<&str>,
616) -> Option<String> {
617    let image = image.filter(|i| ctx.referenced && !i.data.is_empty())?;
618    if !typst_decodes(&image.mimetype) {
619        return None;
620    }
621    let path = format!(
622        "{}/image_{:06}.{}",
623        ctx.artifacts_dir,
624        ctx.pic_index,
625        crate::markdown::ext_for(&image.mimetype)
626    );
627    ctx.pic_index += 1;
628    ctx.artifacts.push((path.clone(), image.data.clone()));
629    let mut call = format!("image({}", string_lit(&path));
630    // The displayed size (inches, #834), when the format records one.
631    if let Some([w, _]) = image.display_size.filter(|[w, h]| *w > 0.0 && *h > 0.0) {
632        call.push_str(&format!(", width: {:.2}in", w));
633    }
634    if let Some(alt) = alt.map(str::trim).filter(|a| !a.is_empty()) {
635        call.push_str(&format!(", alt: {}", string_lit(alt)));
636    }
637    call.push(')');
638    Some(call)
639}
640
641/// `#figure(body, caption: […])`, or the bare `#image(…)` / placeholder
642/// without a caption.
643fn figure(body: Option<String>, caption: Option<&str>) -> String {
644    let caption = caption.map(inline_cell).filter(|c| !c.trim().is_empty());
645    match (body, caption) {
646        (Some(b), Some(c)) => format!("#figure(\n  {b},\n  caption: [{c}],\n)"),
647        (Some(b), None) => format!("#{b}"),
648        (None, Some(c)) => format!("#figure(\n  [{IMAGE_PLACEHOLDER}],\n  caption: [{c}],\n)"),
649        (None, None) => IMAGE_PLACEHOLDER.to_string(),
650    }
651}
652
653/// One cell's content: a rich cell's blocks rendered as markup, else the
654/// flat text.
655fn cell_content(ctx: &mut Ctx, t: &Table, anchor: (usize, usize), flat: &str) -> String {
656    let blocks = t
657        .cell_blocks
658        .as_ref()
659        .and_then(|b| b.get(anchor.0))
660        .and_then(|row| row.get(anchor.1))
661        .filter(|b| !b.is_empty());
662    match blocks {
663        Some(blocks) => render_nodes(ctx, blocks, 0).join("\n\n"),
664        None => inline_cell(flat),
665    }
666}
667
668/// `#table(columns: N, …)`: first-class cells at their anchors (spans as
669/// `table.cell(colspan:, rowspan:)`, positions no cell covers as `[]`),
670/// else the padded row grid; leading all-header rows go in `table.header`.
671fn render_table(ctx: &mut Ctx, t: &Table) -> String {
672    let num_rows = t.rows.len();
673    let num_cols = t.rows.iter().map(Vec::len).max().unwrap_or(0);
674    let mut rows: Vec<Vec<String>> = vec![Vec::new(); num_rows];
675    let mut header_rows = 0usize;
676    match t.cells.as_ref().filter(|c| !c.is_empty()) {
677        Some(cells) => {
678            // Each cell placed at its anchor with its span clamped to the
679            // grid; a cell overlapping one placed before it keeps only its
680            // anchor (or is dropped when that is taken too) — Typst rejects
681            // overlapping spans.
682            struct Placed {
683                k: usize,
684                rs: usize,
685                cs: usize,
686            }
687            let mut owner = vec![vec![None::<usize>; num_cols]; num_rows];
688            let mut placed: Vec<Placed> = Vec::new();
689            for (k, c) in cells.iter().enumerate() {
690                let (r0, c0) = (c.start_row, c.start_col);
691                if r0 >= num_rows || c0 >= num_cols || owner[r0][c0].is_some() {
692                    continue;
693                }
694                let mut rs = c.row_span.max(1).min(num_rows - r0);
695                let mut cs = c.col_span.max(1).min(num_cols - c0);
696                let free = (r0..r0 + rs).all(|r| (c0..c0 + cs).all(|q| owner[r][q].is_none()));
697                if !free {
698                    (rs, cs) = (1, 1);
699                }
700                for row in owner.iter_mut().skip(r0).take(rs) {
701                    for slot in row.iter_mut().skip(c0).take(cs) {
702                        *slot = Some(placed.len());
703                    }
704                }
705                placed.push(Placed { k, rs, cs });
706            }
707            // The header: the longest run of leading rows wholly covered by
708            // column-header cells that do not span past it (and leaving a
709            // body under it).
710            for h in 1..num_rows {
711                let rows_ok = (0..h).all(|r| {
712                    (0..num_cols).all(|c| {
713                        owner[r][c].is_some_and(|p| {
714                            let cell = &cells[placed[p].k];
715                            cell.column_header && cell.start_row + placed[p].rs <= h
716                        })
717                    })
718                });
719                if !rows_ok {
720                    break;
721                }
722                header_rows = h;
723            }
724            // Row-major at the anchors: Typst's auto-placement skips the
725            // positions a span covers, and a position no cell covers is an
726            // empty cell.
727            for (r, owned) in owner.iter().enumerate() {
728                for (c, slot) in owned.iter().enumerate() {
729                    match *slot {
730                        Some(p) => {
731                            let Placed { k, rs, cs } = placed[p];
732                            let cell = &cells[k];
733                            if cell.start_row != r || cell.start_col != c {
734                                continue;
735                            }
736                            let content = cell_content(ctx, t, (r, c), &cell.text);
737                            rows[r].push(if cs > 1 || rs > 1 {
738                                let mut args = Vec::new();
739                                if cs > 1 {
740                                    args.push(format!("colspan: {cs}"));
741                                }
742                                if rs > 1 {
743                                    args.push(format!("rowspan: {rs}"));
744                                }
745                                format!("table.cell({})[{content}]", args.join(", "))
746                            } else {
747                                format!("[{content}]")
748                            });
749                        }
750                        None => rows[r].push("[]".to_string()),
751                    }
752                }
753            }
754        }
755        None => {
756            for (r, row) in t.rows.iter().enumerate() {
757                for c in 0..num_cols {
758                    let flat = row.get(c).map(String::as_str).unwrap_or("");
759                    let content = cell_content(ctx, t, (r, c), flat);
760                    rows[r].push(format!("[{content}]"));
761                }
762            }
763            // The default structure: row 0 is the header (Markdown's
764            // reading), when there is a body under it.
765            let declared = t
766                .structure
767                .as_ref()
768                .map(|s| s.header_row.iter().take_while(|h| **h).count());
769            header_rows = match declared {
770                Some(h) => h.min(num_rows),
771                None => usize::from(num_rows > 1),
772            };
773            if header_rows == num_rows {
774                header_rows = 0;
775            }
776        }
777    }
778    let caption = t
779        .caption
780        .as_deref()
781        .map(inline_cell)
782        .filter(|c| !c.trim().is_empty());
783    let notes: Vec<String> = t
784        .footnotes
785        .iter()
786        .map(|n| inline_md(n))
787        .filter(|n| !n.trim().is_empty())
788        .collect();
789    if num_cols == 0 {
790        let mut out: Vec<String> = caption.into_iter().collect();
791        out.extend(notes);
792        return out.join("\n\n");
793    }
794    let mut lines = vec![format!("table(\n  columns: {num_cols},")];
795    if header_rows > 0 {
796        lines.push("  table.header(".to_string());
797        for row in &rows[..header_rows] {
798            if !row.is_empty() {
799                lines.push(format!("    {},", row.join(", ")));
800            }
801        }
802        lines.push("  ),".to_string());
803    }
804    for row in &rows[header_rows..] {
805        if !row.is_empty() {
806            lines.push(format!("  {},", row.join(", ")));
807        }
808    }
809    lines.push(")".to_string());
810    let table = lines.join("\n");
811    let block = match caption {
812        Some(c) => {
813            let indented = table.replace('\n', "\n  ");
814            format!("#figure(\n  {indented},\n  caption: [{c}],\n)")
815        }
816        None => format!("#{table}"),
817    };
818    let mut out = vec![block];
819    out.extend(notes);
820    out.join("\n\n")
821}
822
823// ---------------------------------------------------------------------------
824// Lists
825// ---------------------------------------------------------------------------
826
827fn level_of(node: &Node) -> u8 {
828    match node {
829        Node::ListItem { level, .. } => *level,
830        _ => 0,
831    }
832}
833
834/// Split a run of list items into sibling lists at the base level, at the
835/// backend's `first_in_list` boundaries (as the Markdown / LaTeX exports).
836fn sibling_lists(run: &[Node]) -> Vec<&[Node]> {
837    let base = level_of(&run[0]);
838    let mut groups = Vec::new();
839    let mut seg = 0;
840    for k in 0..run.len() {
841        let Node::ListItem {
842            first_in_list,
843            level,
844            ..
845        } = &run[k]
846        else {
847            continue;
848        };
849        if *level != base {
850            continue;
851        }
852        if k > seg && *first_in_list {
853            groups.push(&run[seg..k]);
854            seg = k;
855        }
856    }
857    groups.push(&run[seg..]);
858    groups
859}
860
861/// One list: `- item` / `+ item` lines indented by `depth` steps of two
862/// spaces; deeper successors nest one step further. An item's continuation
863/// lines are indented under its text. Two sibling lists in a row are
864/// separated by a blank line, which Typst keeps as two lists.
865fn render_list(items: &[Node], depth: usize) -> String {
866    let base = level_of(&items[0]);
867    let pad = "  ".repeat(depth);
868    let mut lines: Vec<String> = Vec::new();
869    let mut i = 0;
870    while i < items.len() {
871        let Node::ListItem {
872            text,
873            dclx,
874            layer,
875            ordered,
876            ..
877        } = &items[i]
878        else {
879            i += 1;
880            continue;
881        };
882        if level_of(&items[i]) > base {
883            i += 1;
884            continue;
885        }
886        let mut j = i + 1;
887        while j < items.len() && level_of(&items[j]) > base {
888            j += 1;
889        }
890        if layer.is_none() {
891            let ordered = dclx.as_ref().map_or(*ordered, |d| d.ordered);
892            let text = dclx
893                .as_ref()
894                .filter(|d| !d.text.is_empty())
895                .map_or(text.as_str(), |d| d.text.as_str());
896            let marker = if ordered { "+" } else { "-" };
897            let body = inline_md(text).replace('\n', &format!("\n{pad}  "));
898            lines.push(format!("{pad}{marker} {body}").trim_end().to_string());
899            if j > i + 1 {
900                let nested: Vec<Node> = items[i + 1..j]
901                    .iter()
902                    .filter(|n| matches!(n, Node::ListItem { .. }))
903                    .cloned()
904                    .collect();
905                if !nested.is_empty() {
906                    for group in sibling_lists(&nested) {
907                        let text = render_list(group, depth + 1);
908                        if !text.is_empty() {
909                            lines.push(text);
910                        }
911                    }
912                }
913            }
914        }
915        i = j;
916    }
917    lines.join("\n")
918}
919
920// ---------------------------------------------------------------------------
921// LaTeX math → Typst math
922// ---------------------------------------------------------------------------
923
924/// Translate a LaTeX math source into Typst math, or `None` when it uses a
925/// construct outside the supported subset (environments, alignment `&`,
926/// `\\` rows, unknown macros) — the caller then keeps the LaTeX verbatim.
927/// Literal delimiters are backslash-escaped so they never group, letters
928/// are spaced apart (Typst reads `ab` as one identifier), symbols are
929/// written as their Unicode characters (stable across Typst versions,
930/// unlike the symbol names).
931pub fn latex_to_typst_math(latex: &str) -> Option<String> {
932    let chars: Vec<char> = latex.chars().collect();
933    let mut p = MathParser { chars, pos: 0 };
934    let out = p.seq(false)?;
935    if p.pos != p.chars.len() {
936        return None;
937    }
938    let out = out.trim().to_string();
939    (!out.is_empty()).then_some(out)
940}
941
942struct MathParser {
943    chars: Vec<char>,
944    pos: usize,
945}
946
947const MATH_FUNCS: &[&str] = &[
948    "sin", "cos", "tan", "cot", "sec", "csc", "sinh", "cosh", "tanh", "coth", "arcsin", "arccos",
949    "arctan", "log", "ln", "lg", "exp", "lim", "liminf", "limsup", "max", "min", "sup", "inf",
950    "det", "dim", "ker", "deg", "gcd", "arg", "Pr",
951];
952
953fn math_symbol(name: &str) -> Option<&'static str> {
954    Some(match name {
955        "alpha" => "α",
956        "beta" => "β",
957        "gamma" => "γ",
958        "delta" => "δ",
959        "epsilon" => "ϵ",
960        "varepsilon" => "ε",
961        "zeta" => "ζ",
962        "eta" => "η",
963        "theta" => "θ",
964        "vartheta" => "ϑ",
965        "iota" => "ι",
966        "kappa" => "κ",
967        "lambda" => "λ",
968        "mu" => "μ",
969        "nu" => "ν",
970        "xi" => "ξ",
971        "pi" => "π",
972        "varpi" => "ϖ",
973        "rho" => "ρ",
974        "varrho" => "ϱ",
975        "sigma" => "σ",
976        "varsigma" => "ς",
977        "tau" => "τ",
978        "upsilon" => "υ",
979        "phi" => "ϕ",
980        "varphi" => "φ",
981        "chi" => "χ",
982        "psi" => "ψ",
983        "omega" => "ω",
984        "Gamma" => "Γ",
985        "Delta" => "Δ",
986        "Theta" => "Θ",
987        "Lambda" => "Λ",
988        "Xi" => "Ξ",
989        "Pi" => "Π",
990        "Sigma" => "Σ",
991        "Upsilon" => "Υ",
992        "Phi" => "Φ",
993        "Psi" => "Ψ",
994        "Omega" => "Ω",
995        "cdot" => "⋅",
996        "times" => "×",
997        "div" => "÷",
998        "pm" => "±",
999        "mp" => "∓",
1000        "ast" => "∗",
1001        "star" => "⋆",
1002        "circ" => "∘",
1003        "bullet" => "∙",
1004        "leq" | "le" => "≤",
1005        "geq" | "ge" => "≥",
1006        "neq" | "ne" => "≠",
1007        "ll" => "≪",
1008        "gg" => "≫",
1009        "approx" => "≈",
1010        "equiv" => "≡",
1011        "sim" => "∼",
1012        "simeq" => "≃",
1013        "cong" => "≅",
1014        "propto" => "∝",
1015        "infty" => "∞",
1016        "partial" => "∂",
1017        "nabla" => "∇",
1018        "sum" => "∑",
1019        "prod" => "∏",
1020        "coprod" => "∐",
1021        "int" => "∫",
1022        "iint" => "∬",
1023        "iiint" => "∭",
1024        "oint" => "∮",
1025        "in" => "∈",
1026        "notin" => "∉",
1027        "ni" => "∋",
1028        "subset" => "⊂",
1029        "subseteq" => "⊆",
1030        "supset" => "⊃",
1031        "supseteq" => "⊇",
1032        "cup" => "∪",
1033        "cap" => "∩",
1034        "bigcup" => "⋃",
1035        "bigcap" => "⋂",
1036        "setminus" => "∖",
1037        "emptyset" | "varnothing" => "∅",
1038        "forall" => "∀",
1039        "exists" => "∃",
1040        "neg" | "lnot" => "¬",
1041        "land" | "wedge" => "∧",
1042        "lor" | "vee" => "∨",
1043        "oplus" => "⊕",
1044        "otimes" => "⊗",
1045        "to" | "rightarrow" => "→",
1046        "leftarrow" | "gets" => "←",
1047        "leftrightarrow" => "↔",
1048        "Rightarrow" | "implies" => "⇒",
1049        "Leftarrow" => "⇐",
1050        "Leftrightarrow" | "iff" => "⇔",
1051        "mapsto" => "↦",
1052        "uparrow" => "↑",
1053        "downarrow" => "↓",
1054        "ldots" | "dots" => "…",
1055        "cdots" => "⋯",
1056        "vdots" => "⋮",
1057        "ddots" => "⋱",
1058        "langle" => "⟨",
1059        "rangle" => "⟩",
1060        "lfloor" => "⌊",
1061        "rfloor" => "⌋",
1062        "lceil" => "⌈",
1063        "rceil" => "⌉",
1064        "hbar" => "ℏ",
1065        "ell" => "ℓ",
1066        "Re" => "ℜ",
1067        "Im" => "ℑ",
1068        "aleph" => "ℵ",
1069        "prime" => "′",
1070        "perp" => "⊥",
1071        "parallel" => "∥",
1072        "angle" => "∠",
1073        "mid" | "vert" => "|",
1074        "Vert" => "‖",
1075        _ => return None,
1076    })
1077}
1078
1079impl MathParser {
1080    fn peek(&self) -> Option<char> {
1081        self.chars.get(self.pos).copied()
1082    }
1083
1084    fn skip_ws(&mut self) {
1085        while self.peek().is_some_and(char::is_whitespace) {
1086            self.pos += 1;
1087        }
1088    }
1089
1090    /// A command name after `\`: a letter run, or one non-letter.
1091    fn command(&mut self) -> Option<String> {
1092        let start = self.pos;
1093        while self.peek().is_some_and(|c| c.is_ascii_alphabetic()) {
1094            self.pos += 1;
1095        }
1096        if self.pos == start {
1097            let c = self.peek()?;
1098            self.pos += 1;
1099            return Some(c.to_string());
1100        }
1101        Some(self.chars[start..self.pos].iter().collect())
1102    }
1103
1104    /// Tokens up to the end, or to the `}` closing a group when `group`.
1105    fn seq(&mut self, group: bool) -> Option<String> {
1106        let mut out = String::new();
1107        loop {
1108            self.skip_ws();
1109            match self.peek() {
1110                None if group => return None,
1111                None => return Some(out),
1112                Some('}') if group => {
1113                    self.pos += 1;
1114                    return Some(out);
1115                }
1116                Some('}') => return None,
1117                Some('^' | '_') => {
1118                    let op = self.peek()?;
1119                    self.pos += 1;
1120                    let arg = self.argument()?;
1121                    if out.trim_end().is_empty() {
1122                        out.push_str("\"\"");
1123                    }
1124                    while out.ends_with(' ') {
1125                        out.pop();
1126                    }
1127                    out.push(op);
1128                    out.push('(');
1129                    out.push_str(&arg);
1130                    out.push_str(") ");
1131                }
1132                Some('\'') => {
1133                    self.pos += 1;
1134                    while out.ends_with(' ') {
1135                        out.pop();
1136                    }
1137                    out.push_str("' ");
1138                }
1139                Some(_) => {
1140                    let atom = self.atom()?;
1141                    if !atom.is_empty() {
1142                        out.push_str(&atom);
1143                        out.push(' ');
1144                    }
1145                }
1146            }
1147        }
1148    }
1149
1150    /// A script's / macro's argument: a `{…}` group or one atom.
1151    fn argument(&mut self) -> Option<String> {
1152        self.skip_ws();
1153        match self.peek()? {
1154            '{' => {
1155                self.pos += 1;
1156                Some(self.seq(true)?.trim().to_string())
1157            }
1158            '}' | '^' | '_' => None,
1159            // TeX reads an unbraced argument as one token, so `\frac37` is
1160            // `\frac{3}{7}` and `x^23` is `x^{2}3` — never the digit run
1161            // `atom` reads in a sequence (#1255).
1162            c if c.is_ascii_digit() => {
1163                self.pos += 1;
1164                Some(c.to_string())
1165            }
1166            _ => Some(self.atom()?.trim().to_string()),
1167        }
1168    }
1169
1170    /// A function call's argument: [`Self::argument`], refused when it
1171    /// holds a top-level `,` / `;` (they would split the call's arguments).
1172    fn call_argument(&mut self) -> Option<String> {
1173        let arg = self.argument()?;
1174        let mut depth = 0i32;
1175        let mut prev = ' ';
1176        for c in arg.chars() {
1177            match c {
1178                '(' if prev != '\\' => depth += 1,
1179                ')' if prev != '\\' => depth -= 1,
1180                ',' | ';' if depth == 0 && prev != '\\' => return None,
1181                _ => {}
1182            }
1183            prev = c;
1184        }
1185        (!arg.is_empty()).then_some(arg)
1186    }
1187
1188    /// The text of a `{…}` argument read verbatim (`\text{…}`).
1189    fn text_argument(&mut self) -> Option<String> {
1190        self.skip_ws();
1191        if self.peek()? != '{' {
1192            return None;
1193        }
1194        self.pos += 1;
1195        let start = self.pos;
1196        let mut depth = 0usize;
1197        while let Some(c) = self.peek() {
1198            match c {
1199                '{' => depth += 1,
1200                '}' if depth == 0 => {
1201                    let text: String = self.chars[start..self.pos].iter().collect();
1202                    self.pos += 1;
1203                    return Some(text);
1204                }
1205                '}' => depth -= 1,
1206                '\\' => return None,
1207                _ => {}
1208            }
1209            self.pos += 1;
1210        }
1211        None
1212    }
1213
1214    fn atom(&mut self) -> Option<String> {
1215        let c = self.peek()?;
1216        self.pos += 1;
1217        Some(match c {
1218            '{' => self.seq(true)?.trim().to_string(),
1219            '\\' => return self.macro_atom(),
1220            c if c.is_ascii_digit() => {
1221                let start = self.pos - 1;
1222                while self.peek().is_some_and(|d| d.is_ascii_digit() || d == '.') {
1223                    self.pos += 1;
1224                }
1225                let mut num: String = self.chars[start..self.pos].iter().collect();
1226                // A trailing `.` is punctuation, not a decimal point.
1227                if num.ends_with('.') {
1228                    num.pop();
1229                    self.pos -= 1;
1230                }
1231                num
1232            }
1233            c if c.is_alphabetic() => c.to_string(),
1234            '+' | '-' | '=' | '<' | '>' | ',' | ';' | ':' | '!' | '|' | '?' | '.' => c.to_string(),
1235            '*' => "∗".to_string(),
1236            '(' | ')' | '[' | ']' | '/' => format!("\\{c}"),
1237            '~' => String::new(),
1238            c if !c.is_ascii() && !c.is_control() => c.to_string(),
1239            _ => return None,
1240        })
1241    }
1242
1243    fn macro_atom(&mut self) -> Option<String> {
1244        let name = self.command()?;
1245        if let Some(sym) = math_symbol(&name) {
1246            return Some(sym.to_string());
1247        }
1248        if MATH_FUNCS.contains(&name.as_str()) {
1249            return Some(name);
1250        }
1251        Some(match name.as_str() {
1252            "frac" | "dfrac" | "tfrac" => {
1253                let num = self.call_argument()?;
1254                let den = self.call_argument()?;
1255                format!("frac({num}, {den})")
1256            }
1257            "sqrt" => {
1258                self.skip_ws();
1259                if self.peek() == Some('[') {
1260                    self.pos += 1;
1261                    let start = self.pos;
1262                    while self.peek().is_some_and(|c| c != ']') {
1263                        self.pos += 1;
1264                    }
1265                    let index: String = self.chars[start..self.pos].iter().collect();
1266                    self.peek()?;
1267                    self.pos += 1;
1268                    let index = latex_to_typst_math(&index)?;
1269                    if index.contains([',', ';']) {
1270                        return None;
1271                    }
1272                    let radicand = self.call_argument()?;
1273                    format!("root({index}, {radicand})")
1274                } else {
1275                    format!("sqrt({})", self.call_argument()?)
1276                }
1277            }
1278            "mathbf" | "boldsymbol" | "bm" => format!("bold({})", self.call_argument()?),
1279            "mathit" => format!("italic({})", self.call_argument()?),
1280            "mathcal" => format!("cal({})", self.call_argument()?),
1281            "mathbb" => format!("bb({})", self.call_argument()?),
1282            "mathfrak" => format!("frak({})", self.call_argument()?),
1283            "mathsf" => format!("sans({})", self.call_argument()?),
1284            "mathtt" => format!("mono({})", self.call_argument()?),
1285            "mathrm" | "text" | "textrm" | "textit" | "textbf" | "mbox" => {
1286                string_lit(&self.text_argument()?)
1287            }
1288            "operatorname" => format!("op({})", string_lit(&self.text_argument()?)),
1289            "hat" | "widehat" => format!("hat({})", self.call_argument()?),
1290            "bar" | "overline" => format!("overline({})", self.call_argument()?),
1291            "underline" => format!("underline({})", self.call_argument()?),
1292            "tilde" | "widetilde" => format!("tilde({})", self.call_argument()?),
1293            "vec" => format!("arrow({})", self.call_argument()?),
1294            // `\boxed{…}` (amsmath) frames its argument; Typst's `box` called
1295            // in math keeps the body math, named arguments take `#` values.
1296            // Common in worked answers, so unsupported it sent the whole
1297            // formula back to raw LaTeX (#1255).
1298            "boxed" => format!(
1299                "box(stroke: #0.5pt, inset: #3pt, {})",
1300                self.call_argument()?
1301            ),
1302            "dot" => format!("dot({})", self.call_argument()?),
1303            "ddot" => format!("dot.double({})", self.call_argument()?),
1304            // Sizing hints: the delimiter that follows is kept as a literal.
1305            "left" | "right" | "big" | "Big" | "bigg" | "Bigg" | "bigl" | "bigr" | "Bigl"
1306            | "Bigr" => {
1307                self.skip_ws();
1308                if self.peek() == Some('.') {
1309                    self.pos += 1;
1310                }
1311                String::new()
1312            }
1313            "displaystyle" | "textstyle" | "limits" | "nolimits" => String::new(),
1314            "," | "thinspace" => "thin".to_string(),
1315            ":" | ";" | ">" => "med".to_string(),
1316            "!" => String::new(),
1317            " " => "space".to_string(),
1318            "quad" => "quad".to_string(),
1319            "qquad" => "wide".to_string(),
1320            "{" | "}" | "%" | "&" | "#" | "$" | "_" => format!("\\{name}"),
1321            "|" => "‖".to_string(),
1322            _ => return None,
1323        })
1324    }
1325}
1326
1327#[cfg(test)]
1328mod tests {
1329    use super::*;
1330    use crate::document::{DoclingDocument, Node, TableCell};
1331
1332    fn doc(nodes: Vec<Node>) -> DoclingDocument {
1333        let mut d = DoclingDocument::new("t");
1334        d.nodes = nodes;
1335        d
1336    }
1337
1338    fn typ(nodes: Vec<Node>) -> String {
1339        to_typst(&doc(nodes), &TypstExportOptions::default()).0
1340    }
1341
1342    fn para(text: &str) -> Node {
1343        Node::Paragraph { text: text.into() }
1344    }
1345
1346    #[test]
1347    fn empty_document_is_empty() {
1348        assert_eq!(typ(Vec::new()), "");
1349    }
1350
1351    #[test]
1352    fn headings_by_level() {
1353        let out = typ(vec![
1354            Node::Heading {
1355                level: 1,
1356                text: "Title".into(),
1357            },
1358            Node::Heading {
1359                level: 3,
1360                text: "Sub *sec*".into(),
1361            },
1362            para("Body."),
1363        ]);
1364        assert_eq!(out, "= Title\n\n=== Sub #emph[sec]\n\nBody.\n");
1365    }
1366
1367    #[test]
1368    fn escapes_markup_characters() {
1369        assert_eq!(
1370            escape_typst(r"a#b $5 *x* _y_ `c` <l> @r [s] ~ \ end", false),
1371            r"a\#b \$5 \*x\* \_y\_ \`c\` \<l\> \@r \[s\] \~ \\ end"
1372        );
1373        // Line-start markers only at a line start.
1374        assert_eq!(escape_typst("= no heading", true), r"\= no heading");
1375        assert_eq!(escape_typst("- no list", true), r"\- no list");
1376        assert_eq!(escape_typst("+ no enum", true), r"\+ no enum");
1377        assert_eq!(escape_typst("/ no term: x", true), r"\/ no term: x");
1378        assert_eq!(escape_typst("12. no enum", true), r"12\. no enum");
1379        assert_eq!(escape_typst("a - b = c", true), "a - b = c");
1380        // Comments and dash shorthands.
1381        assert_eq!(escape_typst("a // b /* c", false), r"a \// b \/\* c");
1382        assert_eq!(escape_typst("a -- b -? c", false), r"a \-- b \-? c");
1383        // A newline is a line break; the next line is a line start again.
1384        assert_eq!(escape_typst("one\n\n- two", true), "one \\\n\\- two");
1385    }
1386
1387    #[test]
1388    fn inline_formatting_and_links() {
1389        let out = typ(vec![para(
1390            "A **bold** and *it* and ~~gone~~, `x\"y` and [site](https://e.org/a_b) here.",
1391        )]);
1392        assert_eq!(
1393            out,
1394            "A #strong[bold] and #emph[it] and #strike[gone], #raw(\"x\\\"y\") and \
1395             #link(\"https://e.org/a_b\")[site] here.\n"
1396        );
1397        // A `.` or `(` right after an embedded call would continue it.
1398        assert_eq!(typ(vec![para("**a**. (b)")]), "#strong[a]. (b)\n");
1399        assert_eq!(typ(vec![para("**a**.b")]), "#strong[a];.b\n");
1400        assert_eq!(typ(vec![para("**a**(b)")]), "#strong[a];(b)\n");
1401        // An unsafe link keeps its text.
1402        assert_eq!(typ(vec![para("[x](javascript:alert(1))")]), "x\n");
1403    }
1404
1405    #[test]
1406    fn lists_nest_and_order() {
1407        let item = |level: u8, ordered: bool, first: bool, text: &str| Node::ListItem {
1408            ordered,
1409            number: 1,
1410            first_in_list: first,
1411            text: text.into(),
1412            level,
1413            marker: None,
1414            location: None,
1415            dclx: None,
1416            split: None,
1417            href: None,
1418            layer: None,
1419        };
1420        let out = typ(vec![
1421            item(0, false, true, "one"),
1422            item(1, true, true, "one.a"),
1423            item(1, true, false, "one.b"),
1424            item(0, false, false, "two"),
1425            item(0, true, true, "fresh list"),
1426        ]);
1427        assert_eq!(out, "- one\n  + one.a\n  + one.b\n- two\n\n+ fresh list\n");
1428    }
1429
1430    #[test]
1431    fn code_blocks_fence_and_language() {
1432        let out = typ(vec![Node::Code {
1433            language: Some("Python".into()),
1434            text: "print(\"```\")".into(),
1435            orig: None,
1436            pretty: None,
1437        }]);
1438        assert_eq!(out, "````python\nprint(\"```\")\n````\n");
1439    }
1440
1441    #[test]
1442    fn table_with_header_and_spans() {
1443        let cell = |r, c, rs, cs, text: &str, header| TableCell {
1444            text: text.into(),
1445            start_row: r,
1446            start_col: c,
1447            row_span: rs,
1448            col_span: cs,
1449            column_header: header,
1450            bbox: None,
1451            row_header: false,
1452            row_section: false,
1453        };
1454        let mut t = Table {
1455            rows: vec![
1456                vec!["H".into(), "H".into()],
1457                vec!["a".into(), "b".into()],
1458                vec!["a".into(), "c".into()],
1459            ],
1460            ..Default::default()
1461        };
1462        t.cells = Some(vec![
1463            cell(0, 0, 1, 2, "H", true),
1464            cell(1, 0, 2, 1, "a", false),
1465            cell(1, 1, 1, 1, "b", false),
1466            cell(2, 1, 1, 1, "c_d", false),
1467        ]);
1468        t.caption = Some("Cap".into());
1469        t.footnotes = vec!["Note.".into()];
1470        let out = typ(vec![Node::Table(t)]);
1471        assert_eq!(
1472            out,
1473            "#figure(\n  table(\n    columns: 2,\n    table.header(\n      \
1474             table.cell(colspan: 2)[H],\n    ),\n    table.cell(rowspan: 2)[a], [b],\n    \
1475             [c\\_d],\n  ),\n  caption: [Cap],\n)\n\nNote.\n"
1476        );
1477    }
1478
1479    #[test]
1480    fn plain_grid_table() {
1481        let t = Table {
1482            rows: vec![vec!["x".into(), "y".into()], vec!["1".into()]],
1483            ..Default::default()
1484        };
1485        assert_eq!(
1486            typ(vec![Node::Table(t)]),
1487            "#table(\n  columns: 2,\n  table.header(\n    [x], [y],\n  ),\n  [1], [],\n)\n"
1488        );
1489    }
1490
1491    #[test]
1492    fn pictures_placeholder_and_referenced() {
1493        let png = crate::document::PictureImage {
1494            mimetype: "image/png".into(),
1495            width: 1,
1496            height: 1,
1497            data: vec![1, 2, 3],
1498            dpi: 72,
1499            display_size: None,
1500        };
1501        let pic =
1502            |image: Option<crate::document::PictureImage>, caption: Option<&str>| Node::Picture {
1503                caption: caption.map(Into::into),
1504                caption_href: None,
1505                image,
1506                classification: None,
1507                description: None,
1508                caption_parent: Default::default(),
1509                caption_location: None,
1510            };
1511        let d = doc(vec![
1512            pic(Some(png.clone()), Some("A *cap*")),
1513            pic(Some(png.clone()), None),
1514            pic(None, None),
1515        ]);
1516        let (placeholder, files) = to_typst(&d, &TypstExportOptions::default());
1517        assert!(files.is_empty());
1518        assert_eq!(
1519            placeholder,
1520            "#figure(\n  [/* image */],\n  caption: [A #emph[cap]],\n)\n\n/* image */\n\n/* image */\n"
1521        );
1522        let (refd, files) = to_typst(
1523            &d,
1524            &TypstExportOptions {
1525                image_mode: ImageMode::Referenced,
1526                artifacts_dir: "doc_artifacts".into(),
1527            },
1528        );
1529        assert_eq!(
1530            refd,
1531            "#figure(\n  image(\"doc_artifacts/image_000000.png\"),\n  caption: [A #emph[cap]],\n)\
1532             \n\n#image(\"doc_artifacts/image_000001.png\")\n\n/* image */\n"
1533        );
1534        assert_eq!(files.len(), 2);
1535        assert_eq!(files[1].0, "doc_artifacts/image_000001.png");
1536        assert_eq!(files[1].1, vec![1, 2, 3]);
1537    }
1538
1539    #[test]
1540    fn formulas_translate_or_stay_latex() {
1541        assert_eq!(
1542            latex_to_typst_math(r"\frac{a+b}{2} \leq \sqrt{x^{2}} + \alpha_i").as_deref(),
1543            Some("frac(a + b, 2) ≤ sqrt(x^(2)) + α_(i)")
1544        );
1545        assert_eq!(
1546            latex_to_typst_math(r"\sum_{i=1}^{n} \mathbf{x}_i").as_deref(),
1547            Some("∑_(i = 1)^(n) bold(x)_(i)")
1548        );
1549        assert_eq!(
1550            latex_to_typst_math(r"\left( ab \right] / 3.5.").as_deref(),
1551            Some(r"\( a b \] \/ 3.5 .")
1552        );
1553        assert_eq!(
1554            latex_to_typst_math(r"\mathrm{d}x \text{ if } f'(x)").as_deref(),
1555            Some("\"d\" x \" if \" f' \\( x \\)")
1556        );
1557        // Outside the subset → verbatim LaTeX.
1558        assert_eq!(
1559            latex_to_typst_math(r"\begin{pmatrix}a&b\end{pmatrix}"),
1560            None
1561        );
1562        assert_eq!(latex_to_typst_math(r"\frac{a,b}{c}"), None);
1563        assert_eq!(latex_to_typst_math(r"\unknownmacro x"), None);
1564        assert_eq!(latex_to_typst_math("{a"), None);
1565    }
1566
1567    /// #1255: an unbraced argument is one token, `\boxed` frames.
1568    #[test]
1569    fn unbraced_arguments_and_boxed() {
1570        let t = |s: &str| latex_to_typst_math(s);
1571        assert_eq!(t(r"\frac37").as_deref(), Some("frac(3, 7)"));
1572        assert_eq!(
1573            t(r"\frac37\times\frac54").as_deref(),
1574            Some("frac(3, 7) × frac(5, 4)")
1575        );
1576        assert_eq!(
1577            t(r"\frac74-\frac{11}{3}").as_deref(),
1578            Some("frac(7, 4) - frac(11, 3)")
1579        );
1580        assert_eq!(t(r"\frac5{21}").as_deref(), Some("frac(5, 21)"));
1581        assert_eq!(t(r"12+\frac37").as_deref(), Some("12 + frac(3, 7)"));
1582        assert_eq!(t(r"x^23").as_deref(), Some("x^(2) 3"));
1583        assert_eq!(t(r"x_{12}^3.5").as_deref(), Some("x_(12)^(3) . 5"));
1584        assert_eq!(
1585            t(r"x=\boxed{3}").as_deref(),
1586            Some("x = box(stroke: #0.5pt, inset: #3pt, 3)")
1587        );
1588        assert_eq!(
1589            t(r"\boxed{-\frac5{21}}").as_deref(),
1590            Some("box(stroke: #0.5pt, inset: #3pt, - frac(5, 21))")
1591        );
1592        // A top-level `,` would split the call's arguments.
1593        assert_eq!(t(r"\boxed{a,b}"), None);
1594        let out = typ(vec![
1595            para("$$E = mc^2$$"),
1596            para(r"Inline $\alpha$ and $\weird$ and $5 apples."),
1597            Node::Formula {
1598                latex: r"\begin{cases}1\end{cases}".into(),
1599                orig: String::new(),
1600                location: None,
1601            },
1602        ]);
1603        assert_eq!(
1604            out,
1605            "$ E = m c^(2) $\n\nInline $α$ and #raw(\"\\\\weird\", lang: \"latex\") and \\$5 apples.\
1606             \n\n```latex\n\\begin{cases}1\\end{cases}\n```\n"
1607        );
1608    }
1609
1610    #[test]
1611    fn rich_cells_render_their_blocks() {
1612        let t = Table {
1613            rows: vec![vec!["x".into()]],
1614            cell_blocks: Some(vec![vec![vec![para("p1"), para("*p2*")]]]),
1615            ..Default::default()
1616        };
1617        assert_eq!(
1618            typ(vec![Node::Table(t)]),
1619            "#table(\n  columns: 1,\n  [p1\n\n#emph[p2]],\n)\n"
1620        );
1621    }
1622}