43 lines
909 B
Python
43 lines
909 B
Python
"""Escape helpers for LaTeX output."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
|
|
_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}")
|
|
|
|
|
|
_LABEL_RE = re.compile(r"[^\w\-]+", re.UNICODE)
|
|
|
|
|
|
def latex_label(name: str | None, prefix: str = "obj") -> str:
|
|
if not name:
|
|
return prefix
|
|
cleaned = _LABEL_RE.sub("-", name.strip()).strip("-")
|
|
return f"{prefix}:{cleaned or 'x'}"
|