The software you're using is flawed and there's essentially no safe method for making such generated code to work.
The problem is that \text eventually makes an \hbox in which the code is typeset using restricted horizontal mode where $$ has a peculiar behavior. Since display math makes no sense, TeX simply considers $$ as an empty math formula, when in restricted horizontal mode. So your \int appears outside math mode and an error ensues.
TeX now tries to enter math mode before rescanning \int, then finds the closing $ which ends math mode. It finds another one, which starts again math mode and now it finds a misplaced }. Another error.
Fix the software producing that code, which is bad LaTeX under many other respects. To begin with, $$ should never be used in LaTeX.
$$...$$within\text. I guess you want simply\text{text, $\int$, text}. – campa Jul 21 '20 at 07:43$$can be used? – Eric Jul 21 '20 at 07:45$$(which shouldn't be really used in LaTeX anyway) enters display math mode, so you are trying to enter display math within display math. What are you trying to achieve? – campa Jul 21 '20 at 07:47sympy.latex(x)which must return math-mode latex, but for somexthe only thing available to me isx._repr_latex_()which returns text-mode latex. I'm looking for the best way of converting the latter to the former, while breaking as few constructs as possible. This question addresses failings the naive approach ofmath_mode = "\\text{" + text_mode + "}"– Eric Jul 21 '20 at 07:52$$is not latex syntax and makes display math which is not what you want here. – David Carlisle Jul 21 '20 at 08:32$$by$to fix the returned string before using it. – David Carlisle Jul 21 '20 at 08:39\$$,\\$$, etc. – Eric Jul 21 '20 at 13:20\$immediately before a$, so on balance, a win. – David Carlisle Jul 21 '20 at 14:09