Generating tmp.tex from [$$] block adds blank lines, breaking some environments

A card with the following text:

[$$]
\begin{tikzcd}
PB \ar[r, "g^{-1}"] \ar[d, "k_*"']
& PD \ar[d, "h_*"] \\
PC \ar[r, "f^{-1}"']
& PA
\end{tikzcd}
[/$$]

generates the following tmp.tex file:

[... preamble, including the needed \usepackage etc commands, snipped ...]
\begin{displaymath}
\begin{tikzcd}
PB \ar[r, "g^{-1}"] \ar[d, "k_*"']

& PD \ar[d, "h_*"] \\

PC \ar[r, "f^{-1}"']

& PA
\end{tikzcd}

\end{displaymath}
\end{document}

which fails to compile, because of the blank lines. I don’t know why Anki is introducing these blank lines, and I don’t know how to stop it doing so.

Anki version:
Anki 24.06.3 (d678e393)
Python 3.9.18 Qt 6.6.2 PyQt 6.6.1
Platform: macOS-14.7-arm64-arm-64bit

OK, a little more investigation points to the culprit:

In rslib/src/latex.rs, the function strip_html_for_latex is a little too eager at replacing <br( /)?> or <div> with \n: clearly, the Anki card editor introduces these breaks when a new line is manually entered, which then need replacing with a new paragraph for LaTeX to understand. But that should not take place inside the replacement text for a displaymath (or regular math) context.

Solution (and I don’t know enough Rust yet to confidently make a PR for this): in the function extract_latex in the same file, we have:

        let latex = match (caps.get(1), caps.get(2), caps.get(3)) {
            (Some(m), _, _) => m.as_str().into(),
            (_, Some(m), _) => format!("${}$", m.as_str()),
            (_, _, Some(m)) => format!(r"\begin{{displaymath}}{}\end{{displaymath}}", m.as_str()),
            _ => unreachable!(),
        };

Now, if we replace m.as_str() in the two math contexts by something like strip_html_for_latex_math(&m), with:

fn strip_html_for_latex_math(html: &str) -> Cow<str> {
    let mut out: Cow<str> = html.into();
    if let Cow::Owned(o) = LATEX_NEWLINES.replace_all(html, "") {
        out = o.into();
    }

    out
}

(noting that we just remove any <br( /)?> or <div> without replacing them with new lines), then this should not introduce any extraneous newlines into the generated LaTeX file. (I may have got my Rust syntax wrong, so please feel free to take this and correct it!)

1 Like

I’ve logged this on Generating tmp.tex from [$$] block adds blank lines, breaking some environments · Issue #3466 · ankitects/anki · GitHub

1 Like