utilities to fix LaTeX issues

This commit is contained in:
sebastien committed 2026-09-29 10:53:32 +02:00
1 parent 2a4c5f4f7c
commit a56fc6e680
7 files changed
+164 -2

No files matched your search

+10 -1
View File
@@ -48,6 +48,15 @@ def escape_latex_underscores(text: str) -> str:
return "".join(parts)
def escape_latex_percents(text: str) -> str:
r"""Escape percent signs before annotation text is passed to LaTeX.
Unlike underscores, percent signs are comments both inside and outside
math mode. Collapsing an existing escape run keeps cleanup idempotent.
"""
return re.sub(r"\\*%", lambda _match: r"\%", text)
def normalize_overescaped_latex_commands(text: str) -> str:
r"""Collapse doubled command escapes inside LaTeX math environments.
@@ -118,7 +127,7 @@ def clean_string(text: str, lookup: dict[str, str]) -> str:
text = fast_fix(text, lookup).replace("\x00", "")
text = repair_json_escape_corruption(text)
text = normalize_overescaped_latex_commands(text)
return escape_latex_underscores(text)
return escape_latex_percents(escape_latex_underscores(text))
def clean_obj(value: Any, lookup: dict[str, str]) -> Any:
+10
View File
@@ -141,6 +141,13 @@ import subprocess
from .configuration import LATEX_AFTER, LATEX_BEFORE
LATEX_WARNING_MARKER = "[Copienator:latex-warning] "
def report_latex_warning(output_pdf_path) -> None:
"""Emit a stable, machine-readable path alongside human diagnostics."""
print(f"{LATEX_WARNING_MARKER}{Path(output_pdf_path).resolve()}")
def compile_to_pdf(text, output_pdf_path, *, strict=False):
"""Wraps text in standalone header/footer templates and compiles it to PDF."""
@@ -185,6 +192,7 @@ def compile_to_pdf(text, output_pdf_path, *, strict=False):
shutil.move(generated_pdf, output_pdf_path)
if result.returncode != 0:
report_latex_warning(output_pdf_path)
lines = result.stdout.splitlines()
first = next((i for i, line in enumerate(lines) if line.lstrip().startswith("!")), None)
detail = "\n" + "\n".join(lines[first:first + 5]) if first is not None else ""
@@ -196,10 +204,12 @@ def compile_to_pdf(text, output_pdf_path, *, strict=False):
if strict:
raise RuntimeError(f"LaTeX failed for {output_pdf_path}{detail}")
elif not pdf_generated:
report_latex_warning(output_pdf_path)
print(f"Warning: LaTeX compilation produced no PDF for {output_pdf_path}")
if strict:
raise RuntimeError(f"No PDF generated for {output_pdf_path}")
except Exception as e:
if strict:
raise
report_latex_warning(output_pdf_path)
print(f"Compilation error for {output_pdf_path}: {e}")