Skip to content

fix: preserve custom LaTeX env shorthand macros during translation#2273

Open
octo-patch wants to merge 1 commit into
binary-husky:masterfrom
octo-patch:fix/issue-2240-latex-custom-macro-shorthands
Open

fix: preserve custom LaTeX env shorthand macros during translation#2273
octo-patch wants to merge 1 commit into
binary-husky:masterfrom
octo-patch:fix/issue-2240-latex-custom-macro-shorthands

Conversation

@octo-patch

Copy link
Copy Markdown

Fixes #2240

Problem

Physics and math papers frequently define shorthand commands for equation environments using \def or \newcommand, e.g.:

\def\be{\begin{equation}}
\def\ee{\end{equation}}
\def\bea{\begin{eqnarray}}
\def\eea{\end{eqnarray}}

The LaTeX segmentation logic in latex_actions.py only recognized standard \begin{equation}...\end{equation} patterns. When authors used these shorthands, the enclosed math content was not preserved from GPT translation — causing it to be sent for translation (corrupting the math) or replaced with incorrect LaTeX delimiters like \[.

Solution

Added extract_user_defined_env_patterns() in latex_toolbox.py that:

  1. Scans the merged TeX content for \def\cmd{\begin{envname}} and \def\cmd{\end{envname}} declarations (also handles \newcommand / \renewcommand)
  2. Finds matching begin/end pairs for the same environment name
  3. Returns regex patterns for each matched pair with a negative lookahead (?![a-zA-Z]) to avoid false matches on longer commands that share the same prefix (e.g., \be must not match \begin)

These patterns are then applied in split_subprocess() immediately after the standard equation/align patterns, so the custom shorthand blocks are correctly preserved from GPT translation.

Testing

Manually tested with a synthetic TeX document containing \def\be{\begin{equation}} and \def\ee{\end{equation}}:

  • \be...\ee blocks are correctly marked as PRESERVE
  • \begin{equation} is NOT accidentally matched by the \be pattern (negative lookahead works)
  • No changes to existing behavior when no custom shorthands are defined

…ixes binary-husky#2240)

Physics papers commonly define shorthand commands like \def\be{\begin{equation}}.
These shorthands were not recognized by the segmentation logic, causing enclosed
math to be incorrectly sent to GPT for translation.

Add extract_user_defined_env_patterns() to detect \def and \newcommand
declarations that map to \begin{X}/\end{X} pairs, then generate corresponding
preserve patterns with negative lookahead to avoid false matches on longer commands.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: latex公式环境缩写导致编译问题

1 participant