"""Escape helpers for LaTeX output.""" from __future__ import annotations from mdexport.labels import sanitize_label _SPECIAL = { "\\": r"\textbackslash{}", "{": r"\{", "}": r"\}", "#": r"\#", "$": r"\$", "%": r"\%", "&": r"\&", "_": r"\_", "~": r"\textasciitilde{}", "^": r"\textasciicircum{}", } def escape_text(s: str) -> str: if not s: return "" out = [] for ch in s: out.append(_SPECIAL.get(ch, ch)) return "".join(out) def escape_verbatim_for_listing(s: str) -> str: """lstlisting body — avoid ending the environment accidentally.""" return s.replace("\\end{lstlisting}", "\\end\\{lstlisting}") def latex_label(name: str | None, prefix: str = "obj") -> str: return sanitize_label(name, prefix, ":")