fix: handle latex equations when rendering typst

This commit is contained in:
alexm committed 2026-09-14 04:20:15 -04:00
1 parent b375e6c94f
commit 51f095d677
7 files changed
+223 -18

No files matched your search

+68 -1
View File
@@ -1070,8 +1070,61 @@ fn numeric_map(map: &BTreeMap<String, f64>) -> Value {
)
}
/// Emits authored markup as either a content block or a quoted string.
/// Rewrites inline LaTeX math (`$...$`) into a call to mitex's `mi`, so Typst's
/// own math grammar never has to parse it. Typst's `\times`, `\Delta`, `\ln` and
/// friends are not valid Typst math — a bare backslash escapes the next
/// character instead of naming a symbol — which is why equations compile but
/// print wrong instead of failing outright. `\$` is left alone, matching LaTeX's
/// own convention for a literal dollar sign, and a `$` with no matching close is
/// left alone too, rather than swallowing the rest of the field.
fn rewrite_latex_math(source: &str) -> String {
let chars: Vec<(usize, char)> = source.char_indices().collect();
let mut out = String::with_capacity(source.len());
let mut i = 0;
while i < chars.len() {
let (_, c) = chars[i];
if c == '\\' && i + 1 < chars.len() {
out.push('\\');
out.push(chars[i + 1].1);
i += 2;
continue;
}
if c != '$' {
out.push(c);
i += 1;
continue;
}
let mut j = i + 1;
let close = loop {
if j >= chars.len() {
break None;
}
match chars[j].1 {
'\\' => j += 2,
'$' => break Some(j),
_ => j += 1,
}
};
match close {
Some(close_idx) => {
let start = chars[i + 1].0;
let end = chars[close_idx].0;
out.push_str("#mi(");
out.push_str(&Value::str(&source[start..end]).to_typst(0));
out.push(')');
i = close_idx + 1;
}
None => {
out.push('$');
i += 1;
}
}
}
out
}
fn markup_value(source: &str, content: bool) -> Value {
let source = rewrite_latex_math(source);
if content {
Value::content(source)
} else {
@@ -1221,3 +1274,17 @@ mod tests {
assert!(!balanced("closing ] first"));
}
}
#[test]
fn latex_math_becomes_a_mitex_call() {
assert_eq!(
rewrite_latex_math("angle $\\phi$ (phi)"),
"angle #mi(\"\\\\phi\") (phi)"
);
}
#[test]
fn escaped_and_unmatched_dollar_signs_are_left_alone() {
assert_eq!(rewrite_latex_math("costs \\$5 total"), "costs \\$5 total");
assert_eq!(rewrite_latex_math("just $5"), "just $5");
}