R markdown preview for latex equations sometimes works and then knitr pdf generation fails.
This sometimes seems to happen for me if there are blank lines in equation or some strangenesses in RMardown latex document e.g.:
---
title: "test"
output: pdf_document
---
Works in Rstudio but not in knitr:
$$
\tilde a^\tilde b
$$
Works in both:
$$
{\tilde a}^{\tilde b}
$$
These differences are tricky to debug, The question is: what engine is RStudio using to generate the previews? Can I use the exact same engine with knitr to generate the pdf output? If so how?
Based on a little digging through some StackOverflow questions and GitHub issues, it seems like RStudio is using MathJax to render the inline previews. It may be the case that some pre-processing is done behind the scenes that strips unnecessary whitespace before rendering the preview, and this same whitespace may trip up pdflatex/xelatex/lualatex, which are the three supported LaTeX rendering engines.
I'm not sure that much can be done here - though I do agree that it is a little frustrating that a preview renders, suggesting no issues, only to fail during document rendering.