Files
md_to_gost/md2latex/escape.py
T
Igor20264 516abe7b83
Python application / build (push) Has been cancelled
BigUpdate
2026-09-03 10:44:08 +03:00

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'}"