Repository navigation
Description
Description
mammoth.convert_to_html (and any other entry point that exercises body_xml.read_fld_char) crashes with IndexError: pop from empty list when it encounters a <w:fldChar w:fldCharType="end"/> (or "separate") that has no matching prior "begin" element.
The root cause is in mammoth/docx/body_xml.py:
def read_fld_char(element):
fld_char_type = element.attributes.get("w:fldCharType")
if fld_char_type == "begin":
complex_field_stack.append(...)
...
elif fld_char_type == "end":
complex_field = complex_field_stack.pop() # <-- line 206
...
elif fld_char_type == "separate":
complex_field_separate = complex_field_stack.pop() # <-- line 214
...Both .pop() calls assume the stack is non-empty, which is true for well-formed documents but not guaranteed for arbitrary input. A document whose first fldChar is end (or separate) — for example produced by a buggy DOCX generator, hand-edited, recovered from a partially corrupted file, or carved out of a larger document — leaks IndexError to the caller.
This is similar in shape to #158 ('w:ilvl' when parsing malformed docx numbering), which you accepted and fixed by hardening the malformed-input path.
Reproduction
Minimal standalone repro (no template needed — builds the .docx in memory):
import io, zipfile, mammoth
DOCUMENT_XML = b"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:body>
<w:p>
<w:r><w:fldChar w:fldCharType="end"/></w:r>
<w:r><w:t>Hello</w:t></w:r>
</w:p>
</w:body>
</w:document>"""
CONTENT_TYPES_XML = b"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="xml" ContentType="application/xml"/>
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
</Types>"""
PACKAGE_RELS = b"""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>"""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
z.writestr("[Content_Types].xml", CONTENT_TYPES_XML)
z.writestr("_rels/.rels", PACKAGE_RELS)
z.writestr("word/document.xml", DOCUMENT_XML)
buf.seek(0)
mammoth.convert_to_html(buf)Traceback (HEAD as of 2026-05-24, commit on master):
File ".../mammoth/docx/body_xml.py", line 206, in read_fld_char
complex_field = complex_field_stack.pop()
IndexError: pop from empty list
Switching the fldCharType in the repro to "separate" hits the matching crash on line 214.
Suggested fix
Guard both pops:
elif fld_char_type == "end":
if not complex_field_stack:
return _empty_result
complex_field = complex_field_stack.pop()
...
elif fld_char_type == "separate":
if not complex_field_stack:
return _empty_result
complex_field_separate = complex_field_stack.pop()
...Happy to send a PR if useful.
Context
Found by tailtest, an adversarial test generator I'm building. Filing on behalf of the run; the issue is reproduced and confirmed independently against current master.
Activity
andy-lh-nz commentedon Aug 12, 2026
Corroborating this from production — we hit it on real customer documents, not synthetic input.
Fourteen distinct documents from unrelated customers failed this way in the space of a few weeks: legal contracts and letters in daily use, including one firm's reusable blank template. Via markitdown it surfaces as:
The recurring shape is a complex field whose
beginfldChar is missing while itsinstrTextruns survive. The orphan markers were always in plain runs — never insidew:delor anmc:Fallbackbranch, so this isn't a tracked-changes or markup-compatibility artifact. Contexts includedIFfields in letterhead signature blocks,DOCPROPERTYmerge templates, and nestedREF/PAGEREFin tables of contents, spanning several unrelated document-automation systems.Reproducer, and what Word does with the same file, in the comment below.
mwilliamson commentedon Aug 12, 2026
It would be useful to have any minimal example documents that have been produced by Word.
andy-lh-nz commentedon Aug 13, 2026
Reproducer
Unfortunately we've yet to reproduce this from a pure Word experiment. This reproducer builds a docx that Word reads and renders fine and which is functionally equivalent to the documents we're seeing (of unknown source). It's self-contained (builds the
.docxin memory). Triggers both crash sites in one file: orphanseparate(line 214) as well as orphanend(line 206).Fails identically on 1.11.0 and 1.12.1:
What Word does with the same file
Word opens it without complaint. Re-saving it (we added a trailing newline and saved under a new name) shows Word repairing the markup in two steps:
1. It deletes the orphan markers. Marker sequence before and after:
Three orphans gone; the three well-formed fields untouched; no
begininserted.2. It rewrites the orphaned
instrTextruns as ordinary text. The instrText count drops from 7 to 3 - only those inside well-formed fields survive as instructions. The rest becomew:t:Which is a defensible reading: instruction text with no opening marker isn't an instruction, so it's text.
Implication for the fix
The guard proposed above stops the crash. On this file it yields:
Word renders the same document as:
So the guard silently drops text that Word displays. In our sample that cost real content in a significant fraction of the documents. Elsewhere the dropped text was field plumbing (
REF _Ref234398469 \r \h), which Word also renders literally.Options for fixing are: mammoth should simply not crash; or should match what Word shows. We're matching Word on our side, since "extract what the user sees" is the invariant our product needs.
Provenance
We can't say what produced the imbalance. Word repairs it on save, so these files were most likely last written by something else - legal document-automation tooling is the obvious candidate given our user base. What we can say is that Word opens and renders them fine, so from a user's point of view the document is healthy and the converter is what fails.
Happy to send a PR with the guard plus tests covering both crash sites.
GokouRuri43 commentedon Sep 9, 2026
Confirming this still reproduces on current master. I hit it independently via a real-world document rather than a synthetic repro:
090716_Studentische_Arbeit_VWS.docxfrom LibreOffice core test data (https://github.com/LibreOffice/core/blob/master/sw/qa/extras/ooxmlexport/data/090716_Studentische_Arbeit_VWS.docx). I applied the same two-line guard and added a regression test (test_fld_char_end_without_matching_begin_is_ignoredintests/docx/body_xml_tests.py): it fails on current code and passes with the fix, and the fullbody_xml_tests.py(157 tests) stays green. The branch is atGokouRuri43/python-mammoth:fix/orphaned-fldcharif useful.mwilliamson commentedon Sep 12, 2026
Thanks for the report. This should be now be fixed on
master.