Skip to content

fix: preserve underscores in LaTeX math blocks during DOCX conversion#1924

Open
phanghonghao wants to merge 1 commit into
microsoft:mainfrom
phanghonghao:fix/math-underscore-escaping
Open

fix: preserve underscores in LaTeX math blocks during DOCX conversion#1924
phanghonghao wants to merge 1 commit into
microsoft:mainfrom
phanghonghao:fix/math-underscore-escaping

Conversation

@phanghonghao
Copy link
Copy Markdown

Summary

When converting DOCX files containing OMML math formulas, the conversion pipeline produces incorrect Markdown output because markdownify escapes underscores and asterisks inside LaTeX math delimiters.

Bug: $v_{c}$$v\_{c}$ (broken LaTeX)
Fix: Post-process markdownify output to restore correct LaTeX inside $...$ and $$...$$ math regions.

Root Cause

The DOCX conversion pipeline is:

  1. pre_process.py converts OMML → LaTeX string wrapped in $...$
  2. mammoth converts the modified DOCX → HTML
  3. markdownify converts HTML → Markdown

At step 3, markdownify treats _ and * as emphasis markers and escapes them, even inside math delimiters. This is documented in _markdownify.py line 67: #29: text nodes underscores are escaped.

Changes

  • _markdownify.py: Added _fix_math_escaping() post-processor in convert_soup() that unescapes \__ and \** inside $...$ and $$...$$ math blocks only. Plain-text underscores outside math remain escaped (correct Markdown behavior).
  • test_math_escaping.py: 24 test cases covering:
    • Unit tests for _fix_math_escaping() with various LaTeX patterns
    • Integration tests through _CustomMarkdownify.convert_soup()
    • Regression test ensuring plain-text underscores remain escaped

Test Plan

  • All 24 new tests pass (pytest tests/test_math_escaping.py -v)
  • No regressions in existing test vectors (DOCX, PPTX, PDF, HTML, EPUB, etc.)
  • Verified fix with real DOCX files containing math formulas

🤖 Generated with Claude Code

When converting DOCX files with OMML math formulas, the pipeline
converts OMML → LaTeX ($v_{c}$) → HTML (via mammoth) → Markdown
(via markdownify). The markdownify layer incorrectly escapes
underscores inside math delimiters, producing $v\_{c}$ instead
of $v_{c}$.

Add a post-processing step in `_CustomMarkdownify.convert_soup()`
that restores the correct LaTeX by unescaping `\_` → `_` and
`\*` → `*` inside both inline ($...$) and display ($$...$$) math
regions. Plain-text underscores outside math blocks are preserved
as escaped (correct Markdown behavior).

Related: microsoft#289

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@phanghonghao
Copy link
Copy Markdown
Author

@microsoft-github-policy-service agree

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.

1 participant