markitdown icon indicating copy to clipboard operation
markitdown copied to clipboard

Exposing markdownify options in the docx converter

Open jlevy opened this issue 1 year ago • 2 comments

There are some features in Markdownify that currently don't seem to be exposed or settable in the default configuration. For example, I wanted to customize superscript and subscript conversions (which by default are not formatted when converting docx->md) but this isn't possible by default?

This isn't too hard to fix and it might be useful to expose these. Note the markdownify options are themselves well documented.

So I just thought I'd mention this limitation and share a workaround below. It may be worth simply putting this into the existing DocxConverter:

import sys
from typing import Any, BinaryIO

import mammoth
from markitdown._base_converter import DocumentConverterResult
from markitdown._exceptions import MISSING_DEPENDENCY_MESSAGE, MissingDependencyException
from markitdown._stream_info import StreamInfo
from markitdown.converters._docx_converter import DocxConverter
from typing_extensions import override

# Based on markitdown.converters._docx_converter.DocxConverter.

_dependency_exc_info = None
try:
    import mammoth
except ImportError:
    _dependency_exc_info = sys.exc_info()

# Accepted types (copied exactly from original DocxConverter)
ACCEPTED_MIME_TYPE_PREFIXES = [
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
]
ACCEPTED_FILE_EXTENSIONS = [".docx"]


class CustomDocxConverter(DocxConverter):
    """
    A custom DocxConverter derived from the original, modified only
    to allow passing markdownify options to the underlying markdownify
    HtmlConverter.

    See options:
    https://github.com/matthewwithanm/python-markdownify
    """

    def __init__(self, markdownify_options: dict[str, Any] | None = None):
        """
        Initializes the converter, storing custom markdownify options.
        """
        super().__init__()  # Call base class init (initializes self._html_converter)
        # Store custom options for markdownify
        self.markdownify_options = markdownify_options if markdownify_options is not None else {}  # pyright: ignore

    @override
    def convert(
        self,
        file_stream: BinaryIO,
        stream_info: StreamInfo,
        **kwargs: Any,  # Options passed from MarkItDown.convert (e.g., llm_client)
    ) -> DocumentConverterResult:
        """
        Converts the DOCX stream using mammoth, then converts the resulting
        HTML to Markdown using the internal HtmlConverter, passing along
        any stored markdownify options.
        """
        # Same as original DocxConverter:
        if _dependency_exc_info is not None:
            raise MissingDependencyException(
                MISSING_DEPENDENCY_MESSAGE.format(
                    converter=type(self).__name__,
                    extension=".docx",
                    feature="docx",
                )
            ) from _dependency_exc_info[1].with_traceback(  # type: ignore[union-attr]  # pyright: ignore
                _dependency_exc_info[2]
            )

        # Changes start here:

        # Extract mammoth-specific options if any are passed via kwargs
        style_map = kwargs.get("style_map", None)

        html_result = mammoth.convert_to_html(file_stream, style_map=style_map)
        html_content = html_result.value

        # Add custom markdownify options to the kwargs.
        combined_options = {**kwargs, **self.markdownify_options}

        # Call the internal HtmlConverter's convert_string method with the combined options.
        return self._html_converter.convert_string(
            html_content, url=stream_info.url, **combined_options
        )

jlevy avatar Apr 26 '25 19:04 jlevy

Update from markitdown==0.1.7: a custom DocxConverter subclass is no longer necessary for the specific subscript/superscript options in the original report. I verified that the public API now passes them through for DOCX:

MarkItDown().convert(
    "fixture.docx",
    sub_symbol="<sub>",
    sup_symbol="<sup>",
).markdown

With a minimal DOCX, the default output is H2O and x2; the call above produces H<sub>2</sub>O and x<sup>2</sup>.

The remaining gap is interface parity and discoverability: the 0.1.7 CLI does not expose these options, and the MarkItDown MCP interface available in my environment accepts only a URI. Rather than surfacing many converter-specific flags independently, one opt-in semantic inline-formatting profile across Python, CLI, and MCP could preserve sub/sup and similar meaningful formatting while leaving the current lightweight output as the default.

Related current evidence: underline remains flattened in 0.1.7 (#35), and inconsistent strikethrough variants are reported in #2340.

cagdasyurekli avatar Aug 25 '26 09:08 cagdasyurekli

Thank you for raising this and sharing the workaround. The public Python API in v0.1.8 now passes Markdownify options through DOCX conversion: sub_symbol="<sub>" and sup_symbol="<sup>" correctly preserve the corresponding formatting without a custom converter subclass. Closing the original API request as addressed; CLI/MCP exposure remains separate work in #2492.

If a requested Markdownify option still does not reach DOCX conversion, please reopen this issue or comment here with an example so we can investigate.

afourney avatar Sep 30 '26 18:09 afourney