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            _ => Some(self.atom()?.trim().to_string()),
1160        }
1161    }
1162
1163    /// A function call's argument: [`Self::argument`], refused when it
1164    /// holds a top-level `,` / `;` (they would split the call's arguments).
1165    fn call_argument(&mut self) -> Option<String> {
1166        let arg = self.argument()?;
1167        let mut depth = 0i32;
1168        let mut prev = ' ';
1169        for c in arg.chars() {
1170            match c {
1171                '(' if prev != '\\' => depth += 1,
1172                ')' if prev != '\\' => depth -= 1,
1173                ',' | ';' if depth == 0 && prev != '\\' => return None,
1174                _ => {}
1175            }
1176            prev = c;
1177        }
1178        (!arg.is_empty()).then_some(arg)
1179    }
1180
1181    /// The text of a `{…}` argument read verbatim (`\text{…}`).
1182    fn text_argument(&mut self) -> Option<String> {
1183        self.skip_ws();
1184        if self.peek()? != '{' {
1185            return None;
1186        }
1187        self.pos += 1;
1188        let start = self.pos;
1189        let mut depth = 0usize;
1190        while let Some(c) = self.peek() {
1191            match c {
1192                '{' => depth += 1,
1193                '}' if depth == 0 => {
1194                    let text: String = self.chars[start..self.pos].iter().collect();
1195                    self.pos += 1;
1196                    return Some(text);
1197                }
1198                '}' => depth -= 1,
1199                '\\' => return None,
1200                _ => {}
1201            }
1202            self.pos += 1;
1203        }
1204        None
1205    }
1206
1207    fn atom(&mut self) -> Option<String> {
1208        let c = self.peek()?;
1209        self.pos += 1;
1210        Some(match c {
1211            '{' => self.seq(true)?.trim().to_string(),
1212            '\\' => return self.macro_atom(),
1213            c if c.is_ascii_digit() => {
1214                let start = self.pos - 1;
1215                while self.peek().is_some_and(|d| d.is_ascii_digit() || d == '.') {
1216                    self.pos += 1;
1217                }
1218                let mut num: String = self.chars[start..self.pos].iter().collect();
1219                // A trailing `.` is punctuation, not a decimal point.
1220                if num.ends_with('.') {
1221                    num.pop();
1222                    self.pos -= 1;
1223                }
1224                num
1225            }
1226            c if c.is_alphabetic() => c.to_string(),
1227            '+' | '-' | '=' | '<' | '>' | ',' | ';' | ':' | '!' | '|' | '?' | '.' => c.to_string(),
1228            '*' => "∗".to_string(),
1229            '(' | ')' | '[' | ']' | '/' => format!("\\{c}"),
1230            '~' => String::new(),
1231            c if !c.is_ascii() && !c.is_control() => c.to_string(),
1232            _ => return None,
1233        })
1234    }
1235
1236    fn macro_atom(&mut self) -> Option<String> {
1237        let name = self.command()?;
1238        if let Some(sym) = math_symbol(&name) {
1239            return Some(sym.to_string());
1240        }
1241        if MATH_FUNCS.contains(&name.as_str()) {
1242            return Some(name);
1243        }
1244        Some(match name.as_str() {
1245            "frac" | "dfrac" | "tfrac" => {
1246                let num = self.call_argument()?;
1247                let den = self.call_argument()?;
1248                format!("frac({num}, {den})")
1249            }
1250            "sqrt" => {
1251                self.skip_ws();
1252                if self.peek() == Some('[') {
1253                    self.pos += 1;
1254                    let start = self.pos;
1255                    while self.peek().is_some_and(|c| c != ']') {
1256                        self.pos += 1;
1257                    }
1258                    let index: String = self.chars[start..self.pos].iter().collect();
1259                    self.peek()?;
1260                    self.pos += 1;
1261                    let index = latex_to_typst_math(&index)?;
1262                    if index.contains([',', ';']) {
1263                        return None;
1264                    }
1265                    let radicand = self.call_argument()?;
1266                    format!("root({index}, {radicand})")
1267                } else {
1268                    format!("sqrt({})", self.call_argument()?)
1269                }
1270            }
1271            "mathbf" | "boldsymbol" | "bm" => format!("bold({})", self.call_argument()?),
1272            "mathit" => format!("italic({})", self.call_argument()?),
1273            "mathcal" => format!("cal({})", self.call_argument()?),
1274            "mathbb" => format!("bb({})", self.call_argument()?),
1275            "mathfrak" => format!("frak({})", self.call_argument()?),
1276            "mathsf" => format!("sans({})", self.call_argument()?),
1277            "mathtt" => format!("mono({})", self.call_argument()?),
1278            "mathrm" | "text" | "textrm" | "textit" | "textbf" | "mbox" => {
1279                string_lit(&self.text_argument()?)
1280            }
1281            "operatorname" => format!("op({})", string_lit(&self.text_argument()?)),
1282            "hat" | "widehat" => format!("hat({})", self.call_argument()?),
1283            "bar" | "overline" => format!("overline({})", self.call_argument()?),
1284            "underline" => format!("underline({})", self.call_argument()?),
1285            "tilde" | "widetilde" => format!("tilde({})", self.call_argument()?),
1286            "vec" => format!("arrow({})", self.call_argument()?),
1287            "dot" => format!("dot({})", self.call_argument()?),
1288            "ddot" => format!("dot.double({})", self.call_argument()?),
1289            // Sizing hints: the delimiter that follows is kept as a literal.
1290            "left" | "right" | "big" | "Big" | "bigg" | "Bigg" | "bigl" | "bigr" | "Bigl"
1291            | "Bigr" => {
1292                self.skip_ws();
1293                if self.peek() == Some('.') {
1294                    self.pos += 1;
1295                }
1296                String::new()
1297            }
1298            "displaystyle" | "textstyle" | "limits" | "nolimits" => String::new(),
1299            "," | "thinspace" => "thin".to_string(),
1300            ":" | ";" | ">" => "med".to_string(),
1301            "!" => String::new(),
1302            " " => "space".to_string(),
1303            "quad" => "quad".to_string(),
1304            "qquad" => "wide".to_string(),
1305            "{" | "}" | "%" | "&" | "#" | "$" | "_" => format!("\\{name}"),
1306            "|" => "‖".to_string(),
1307            _ => return None,
1308        })
1309    }
1310}
1311
1312#[cfg(test)]
1313mod tests {
1314    use super::*;
1315    use crate::document::{DoclingDocument, Node, TableCell};
1316
1317    fn doc(nodes: Vec<Node>) -> DoclingDocument {
1318        let mut d = DoclingDocument::new("t");
1319        d.nodes = nodes;
1320        d
1321    }
1322
1323    fn typ(nodes: Vec<Node>) -> String {
1324        to_typst(&doc(nodes), &TypstExportOptions::default()).0
1325    }
1326
1327    fn para(text: &str) -> Node {
1328        Node::Paragraph { text: text.into() }
1329    }
1330
1331    #[test]
1332    fn empty_document_is_empty() {
1333        assert_eq!(typ(Vec::new()), "");
1334    }
1335
1336    #[test]
1337    fn headings_by_level() {
1338        let out = typ(vec![
1339            Node::Heading {
1340                level: 1,
1341                text: "Title".into(),
1342            },
1343            Node::Heading {
1344                level: 3,
1345                text: "Sub *sec*".into(),
1346            },
1347            para("Body."),
1348        ]);
1349        assert_eq!(out, "= Title\n\n=== Sub #emph[sec]\n\nBody.\n");
1350    }
1351
1352    #[test]
1353    fn escapes_markup_characters() {
1354        assert_eq!(
1355            escape_typst(r"a#b $5 *x* _y_ `c` <l> @r [s] ~ \ end", false),
1356            r"a\#b \$5 \*x\* \_y\_ \`c\` \<l\> \@r \[s\] \~ \\ end"
1357        );
1358        // Line-start markers only at a line start.
1359        assert_eq!(escape_typst("= no heading", true), r"\= no heading");
1360        assert_eq!(escape_typst("- no list", true), r"\- no list");
1361        assert_eq!(escape_typst("+ no enum", true), r"\+ no enum");
1362        assert_eq!(escape_typst("/ no term: x", true), r"\/ no term: x");
1363        assert_eq!(escape_typst("12. no enum", true), r"12\. no enum");
1364        assert_eq!(escape_typst("a - b = c", true), "a - b = c");
1365        // Comments and dash shorthands.
1366        assert_eq!(escape_typst("a // b /* c", false), r"a \// b \/\* c");
1367        assert_eq!(escape_typst("a -- b -? c", false), r"a \-- b \-? c");
1368        // A newline is a line break; the next line is a line start again.
1369        assert_eq!(escape_typst("one\n\n- two", true), "one \\\n\\- two");
1370    }
1371
1372    #[test]
1373    fn inline_formatting_and_links() {
1374        let out = typ(vec![para(
1375            "A **bold** and *it* and ~~gone~~, `x\"y` and [site](https://e.org/a_b) here.",
1376        )]);
1377        assert_eq!(
1378            out,
1379            "A #strong[bold] and #emph[it] and #strike[gone], #raw(\"x\\\"y\") and \
1380             #link(\"https://e.org/a_b\")[site] here.\n"
1381        );
1382        // A `.` or `(` right after an embedded call would continue it.
1383        assert_eq!(typ(vec![para("**a**. (b)")]), "#strong[a]. (b)\n");
1384        assert_eq!(typ(vec![para("**a**.b")]), "#strong[a];.b\n");
1385        assert_eq!(typ(vec![para("**a**(b)")]), "#strong[a];(b)\n");
1386        // An unsafe link keeps its text.
1387        assert_eq!(typ(vec![para("[x](javascript:alert(1))")]), "x\n");
1388    }
1389
1390    #[test]
1391    fn lists_nest_and_order() {
1392        let item = |level: u8, ordered: bool, first: bool, text: &str| Node::ListItem {
1393            ordered,
1394            number: 1,
1395            first_in_list: first,
1396            text: text.into(),
1397            level,
1398            marker: None,
1399            location: None,
1400            dclx: None,
1401            split: None,
1402            href: None,
1403            layer: None,
1404        };
1405        let out = typ(vec![
1406            item(0, false, true, "one"),
1407            item(1, true, true, "one.a"),
1408            item(1, true, false, "one.b"),
1409            item(0, false, false, "two"),
1410            item(0, true, true, "fresh list"),
1411        ]);
1412        assert_eq!(out, "- one\n  + one.a\n  + one.b\n- two\n\n+ fresh list\n");
1413    }
1414
1415    #[test]
1416    fn code_blocks_fence_and_language() {
1417        let out = typ(vec![Node::Code {
1418            language: Some("Python".into()),
1419            text: "print(\"```\")".into(),
1420            orig: None,
1421            pretty: None,
1422        }]);
1423        assert_eq!(out, "````python\nprint(\"```\")\n````\n");
1424    }
1425
1426    #[test]
1427    fn table_with_header_and_spans() {
1428        let cell = |r, c, rs, cs, text: &str, header| TableCell {
1429            text: text.into(),
1430            start_row: r,
1431            start_col: c,
1432            row_span: rs,
1433            col_span: cs,
1434            column_header: header,
1435            bbox: None,
1436            row_header: false,
1437            row_section: false,
1438        };
1439        let mut t = Table {
1440            rows: vec![
1441                vec!["H".into(), "H".into()],
1442                vec!["a".into(), "b".into()],
1443                vec!["a".into(), "c".into()],
1444            ],
1445            ..Default::default()
1446        };
1447        t.cells = Some(vec![
1448            cell(0, 0, 1, 2, "H", true),
1449            cell(1, 0, 2, 1, "a", false),
1450            cell(1, 1, 1, 1, "b", false),
1451            cell(2, 1, 1, 1, "c_d", false),
1452        ]);
1453        t.caption = Some("Cap".into());
1454        t.footnotes = vec!["Note.".into()];
1455        let out = typ(vec![Node::Table(t)]);
1456        assert_eq!(
1457            out,
1458            "#figure(\n  table(\n    columns: 2,\n    table.header(\n      \
1459             table.cell(colspan: 2)[H],\n    ),\n    table.cell(rowspan: 2)[a], [b],\n    \
1460             [c\\_d],\n  ),\n  caption: [Cap],\n)\n\nNote.\n"
1461        );
1462    }
1463
1464    #[test]
1465    fn plain_grid_table() {
1466        let t = Table {
1467            rows: vec![vec!["x".into(), "y".into()], vec!["1".into()]],
1468            ..Default::default()
1469        };
1470        assert_eq!(
1471            typ(vec![Node::Table(t)]),
1472            "#table(\n  columns: 2,\n  table.header(\n    [x], [y],\n  ),\n  [1], [],\n)\n"
1473        );
1474    }
1475
1476    #[test]
1477    fn pictures_placeholder_and_referenced() {
1478        let png = crate::document::PictureImage {
1479            mimetype: "image/png".into(),
1480            width: 1,
1481            height: 1,
1482            data: vec![1, 2, 3],
1483            dpi: 72,
1484            display_size: None,
1485        };
1486        let pic =
1487            |image: Option<crate::document::PictureImage>, caption: Option<&str>| Node::Picture {
1488                caption: caption.map(Into::into),
1489                caption_href: None,
1490                image,
1491                classification: None,
1492                description: None,
1493                caption_parent: Default::default(),
1494                caption_location: None,
1495            };
1496        let d = doc(vec![
1497            pic(Some(png.clone()), Some("A *cap*")),
1498            pic(Some(png.clone()), None),
1499            pic(None, None),
1500        ]);
1501        let (placeholder, files) = to_typst(&d, &TypstExportOptions::default());
1502        assert!(files.is_empty());
1503        assert_eq!(
1504            placeholder,
1505            "#figure(\n  [/* image */],\n  caption: [A #emph[cap]],\n)\n\n/* image */\n\n/* image */\n"
1506        );
1507        let (refd, files) = to_typst(
1508            &d,
1509            &TypstExportOptions {
1510                image_mode: ImageMode::Referenced,
1511                artifacts_dir: "doc_artifacts".into(),
1512            },
1513        );
1514        assert_eq!(
1515            refd,
1516            "#figure(\n  image(\"doc_artifacts/image_000000.png\"),\n  caption: [A #emph[cap]],\n)\
1517             \n\n#image(\"doc_artifacts/image_000001.png\")\n\n/* image */\n"
1518        );
1519        assert_eq!(files.len(), 2);
1520        assert_eq!(files[1].0, "doc_artifacts/image_000001.png");
1521        assert_eq!(files[1].1, vec![1, 2, 3]);
1522    }
1523
1524    #[test]
1525    fn formulas_translate_or_stay_latex() {
1526        assert_eq!(
1527            latex_to_typst_math(r"\frac{a+b}{2} \leq \sqrt{x^{2}} + \alpha_i").as_deref(),
1528            Some("frac(a + b, 2) ≤ sqrt(x^(2)) + α_(i)")
1529        );
1530        assert_eq!(
1531            latex_to_typst_math(r"\sum_{i=1}^{n} \mathbf{x}_i").as_deref(),
1532            Some("∑_(i = 1)^(n) bold(x)_(i)")
1533        );
1534        assert_eq!(
1535            latex_to_typst_math(r"\left( ab \right] / 3.5.").as_deref(),
1536            Some(r"\( a b \] \/ 3.5 .")
1537        );
1538        assert_eq!(
1539            latex_to_typst_math(r"\mathrm{d}x \text{ if } f'(x)").as_deref(),
1540            Some("\"d\" x \" if \" f' \\( x \\)")
1541        );
1542        // Outside the subset → verbatim LaTeX.
1543        assert_eq!(
1544            latex_to_typst_math(r"\begin{pmatrix}a&b\end{pmatrix}"),
1545            None
1546        );
1547        assert_eq!(latex_to_typst_math(r"\frac{a,b}{c}"), None);
1548        assert_eq!(latex_to_typst_math(r"\unknownmacro x"), None);
1549        assert_eq!(latex_to_typst_math("{a"), None);
1550        let out = typ(vec![
1551            para("$$E = mc^2$$"),
1552            para(r"Inline $\alpha$ and $\weird$ and $5 apples."),
1553            Node::Formula {
1554                latex: r"\begin{cases}1\end{cases}".into(),
1555                orig: String::new(),
1556                location: None,
1557            },
1558        ]);
1559        assert_eq!(
1560            out,
1561            "$ E = m c^(2) $\n\nInline $α$ and #raw(\"\\\\weird\", lang: \"latex\") and \\$5 apples.\
1562             \n\n```latex\n\\begin{cases}1\\end{cases}\n```\n"
1563        );
1564    }
1565
1566    #[test]
1567    fn rich_cells_render_their_blocks() {
1568        let t = Table {
1569            rows: vec![vec!["x".into()]],
1570            cell_blocks: Some(vec![vec![vec![para("p1"), para("*p2*")]]]),
1571            ..Default::default()
1572        };
1573        assert_eq!(
1574            typ(vec![Node::Table(t)]),
1575            "#table(\n  columns: 1,\n  [p1\n\n#emph[p2]],\n)\n"
1576        );
1577    }
1578}