Skip to content

converters

Class info

Classes

Name Children Inherits
Registry
mkconvert._core
Name -> backend class mapping, in order of preference.

    Re-exported classes

    Class Module Description
    HtmdConverter mkconvert.converters.htmd htmd: fast Rust converter.
    HtmlToMarkdownConverter mkconvert.converters.base Base class for HTML -> Markdown converters.
    HtmlToMarkdownOptions mkconvert.converters.base Common HTML -> Markdown options, mapped onto every converter.
    MarkdownifyConverter mkconvert.converters.markdownify markdownify: pure-Python converter on top of BeautifulSoup, highly configurable.

    🛈 DocStrings

    HTML -> Markdown converters.

    Importing this package does not import any converter library: each converter imports its library when instantiated.

    registry module-attribute

    registry: Registry[HtmlToMarkdownConverter] = Registry('HTML to Markdown converter')
    

    Converters by name. Order is the preference when no converter is named.

    HtmdConverter

    Bases: HtmlToMarkdownConverter

    htmd: fast Rust converter.

    Not supported: emphasis_marker="_".

    Source code in src/mkconvert/converters/htmd.py
    class HtmdConverter(HtmlToMarkdownConverter):
        """htmd: fast Rust converter.
    
        Not supported: `emphasis_marker="_"`.
        """
    
        name = "htmd"
        requires = ("htmd",)
        extra = "htmd-py"
        supported_options: ClassVar[frozenset[str]] = frozenset({
            "heading_style",
            "bullet_marker",
            "code_block_style",
            "code_fence",
            "line_break",
            "link_style",
            "skip_tags",
        })
    
        def __init__(
            self,
            options: HtmlToMarkdownOptions | None = None,
            *,
            on_unsupported: OnUnsupported = "warn",
            hr_style: Literal["dashes", "asterisks", "underscores"] = "dashes",
            link_reference_style: Literal["full", "collapsed", "shortcut"] = "full",
            preformatted_code: bool = False,
            ul_bullet_spacing: int = 1,
            ol_number_spacing: int = 1,
            translation_mode: Literal["pure", "faithful"] = "pure",
        ) -> None:
            """Create an htmd converter.
    
            Args:
                options: Common options.
                on_unsupported: See `Backend`.
                hr_style: `- - -`, `* * *` or `_ _ _` for `<hr>`.
                link_reference_style: Reference link form (with `link_style="reference"`).
                preformatted_code: Keep whitespace of inline `<code>` as is.
                ul_bullet_spacing: Spaces after a bullet list marker.
                ol_number_spacing: Spaces after an ordered list number.
                translation_mode: `"faithful"` keeps HTML that has no Markdown equivalent.
            """
            super().__init__(options, on_unsupported=on_unsupported)
            import htmd
    
            o = self.options
            opts = htmd.Options()  # ty: ignore[missing-attribute]
            opts.heading_style = "setex" if o.heading_style == "setext" else "atx"
            opts.bullet_list_marker = "dash" if o.bullet_marker == "-" else "asterisk"
            opts.code_block_style = o.code_block_style
            opts.code_block_fence = "tildes" if o.code_fence == "~~~" else "backticks"
            opts.br_style = "backslash" if o.line_break == "backslash" else "two_spaces"
            opts.link_style = "referenced" if o.link_style == "reference" else "inlined"
            opts.skip_tags = [tag.lower() for tag in o.skip_tags]
            opts.hr_style = hr_style
            opts.link_reference_style = link_reference_style
            opts.preformatted_code = preformatted_code
            opts.ul_bullet_spacing = ul_bullet_spacing
            opts.ol_number_spacing = ol_number_spacing
            opts.translation_mode = translation_mode
            self._opts = opts
    
        def convert(self, text: str) -> str:
            """Convert HTML `text` to Markdown."""
            import htmd
    
            return htmd.convert_html(text, self._opts)  # ty: ignore[missing-attribute]
    

    __init__

    __init__(
        options: HtmlToMarkdownOptions | None = None,
        *,
        on_unsupported: OnUnsupported = "warn",
        hr_style: Literal["dashes", "asterisks", "underscores"] = "dashes",
        link_reference_style: Literal["full", "collapsed", "shortcut"] = "full",
        preformatted_code: bool = False,
        ul_bullet_spacing: int = 1,
        ol_number_spacing: int = 1,
        translation_mode: Literal["pure", "faithful"] = "pure",
    ) -> None
    

    Create an htmd converter.

    Parameters:

    Name Type Description Default
    options HtmlToMarkdownOptions | None

    Common options.

    None
    on_unsupported OnUnsupported

    See Backend.

    'warn'
    hr_style Literal['dashes', 'asterisks', 'underscores']

    - - -, * * * or _ _ _ for <hr>.

    'dashes'
    link_reference_style Literal['full', 'collapsed', 'shortcut']

    Reference link form (with link_style="reference").

    'full'
    preformatted_code bool

    Keep whitespace of inline <code> as is.

    False
    ul_bullet_spacing int

    Spaces after a bullet list marker.

    1
    ol_number_spacing int

    Spaces after an ordered list number.

    1
    translation_mode Literal['pure', 'faithful']

    "faithful" keeps HTML that has no Markdown equivalent.

    'pure'
    Source code in src/mkconvert/converters/htmd.py
    def __init__(
        self,
        options: HtmlToMarkdownOptions | None = None,
        *,
        on_unsupported: OnUnsupported = "warn",
        hr_style: Literal["dashes", "asterisks", "underscores"] = "dashes",
        link_reference_style: Literal["full", "collapsed", "shortcut"] = "full",
        preformatted_code: bool = False,
        ul_bullet_spacing: int = 1,
        ol_number_spacing: int = 1,
        translation_mode: Literal["pure", "faithful"] = "pure",
    ) -> None:
        """Create an htmd converter.
    
        Args:
            options: Common options.
            on_unsupported: See `Backend`.
            hr_style: `- - -`, `* * *` or `_ _ _` for `<hr>`.
            link_reference_style: Reference link form (with `link_style="reference"`).
            preformatted_code: Keep whitespace of inline `<code>` as is.
            ul_bullet_spacing: Spaces after a bullet list marker.
            ol_number_spacing: Spaces after an ordered list number.
            translation_mode: `"faithful"` keeps HTML that has no Markdown equivalent.
        """
        super().__init__(options, on_unsupported=on_unsupported)
        import htmd
    
        o = self.options
        opts = htmd.Options()  # ty: ignore[missing-attribute]
        opts.heading_style = "setex" if o.heading_style == "setext" else "atx"
        opts.bullet_list_marker = "dash" if o.bullet_marker == "-" else "asterisk"
        opts.code_block_style = o.code_block_style
        opts.code_block_fence = "tildes" if o.code_fence == "~~~" else "backticks"
        opts.br_style = "backslash" if o.line_break == "backslash" else "two_spaces"
        opts.link_style = "referenced" if o.link_style == "reference" else "inlined"
        opts.skip_tags = [tag.lower() for tag in o.skip_tags]
        opts.hr_style = hr_style
        opts.link_reference_style = link_reference_style
        opts.preformatted_code = preformatted_code
        opts.ul_bullet_spacing = ul_bullet_spacing
        opts.ol_number_spacing = ol_number_spacing
        opts.translation_mode = translation_mode
        self._opts = opts
    

    convert

    convert(text: str) -> str
    

    Convert HTML text to Markdown.

    Source code in src/mkconvert/converters/htmd.py
    def convert(self, text: str) -> str:
        """Convert HTML `text` to Markdown."""
        import htmd
    
        return htmd.convert_html(text, self._opts)  # ty: ignore[missing-attribute]
    

    HtmlToMarkdownConverter

    Bases: Backend[HtmlToMarkdownOptions]

    Base class for HTML -> Markdown converters.

    Source code in src/mkconvert/converters/base.py
    class HtmlToMarkdownConverter(Backend[HtmlToMarkdownOptions]):
        """Base class for HTML -> Markdown converters."""
    
        options_class: ClassVar[type[HtmlToMarkdownOptions]] = HtmlToMarkdownOptions
    

    HtmlToMarkdownOptions

    Bases: Options

    Common HTML -> Markdown options, mapped onto every converter.

    Check HtmlToMarkdownConverter.supported_options for what a converter can change.

    Source code in src/mkconvert/converters/base.py
    class HtmlToMarkdownOptions(Options):
        """Common HTML -> Markdown options, mapped onto every converter.
    
        Check `HtmlToMarkdownConverter.supported_options` for what a converter can change.
        """
    
        heading_style: Literal["atx", "setext"] = "atx"
        """`# Heading` (atx) or underlined headings (setext, h1 / h2 only)."""
        bullet_marker: Literal["-", "*"] = "-"
        """Marker for unordered list items."""
        emphasis_marker: Literal["*", "_"] = "*"
        """Marker for `*emphasis*` and `**strong**`."""
        code_block_style: Literal["fenced", "indented"] = "fenced"
        """Fenced or indented code blocks."""
        code_fence: Literal["```", "~~~"] = "```"
        """Fence for fenced code blocks."""
        line_break: Literal["spaces", "backslash"] = "spaces"
        """`<br>` as two trailing spaces or a trailing backslash."""
        link_style: Literal["inline", "reference"] = "inline"
        """`[text](url)` or `[text][1]` with the URLs collected at the end."""
        skip_tags: tuple[str, ...] = ()
        """Tags to drop together with their content, e.g. `("script", "style")`."""
    

    bullet_marker class-attribute instance-attribute

    bullet_marker: Literal['-', '*'] = '-'
    

    Marker for unordered list items.

    code_block_style class-attribute instance-attribute

    code_block_style: Literal['fenced', 'indented'] = 'fenced'
    

    Fenced or indented code blocks.

    code_fence class-attribute instance-attribute

    code_fence: Literal['```', '~~~'] = '```'
    

    Fence for fenced code blocks.

    emphasis_marker class-attribute instance-attribute

    emphasis_marker: Literal['*', '_'] = '*'
    

    Marker for *emphasis* and **strong**.

    heading_style class-attribute instance-attribute

    heading_style: Literal['atx', 'setext'] = 'atx'
    

    # Heading (atx) or underlined headings (setext, h1 / h2 only).

    line_break class-attribute instance-attribute

    line_break: Literal['spaces', 'backslash'] = 'spaces'
    

    <br> as two trailing spaces or a trailing backslash.

    link_style: Literal['inline', 'reference'] = 'inline'
    

    [text](url) or [text][1] with the URLs collected at the end.

    skip_tags class-attribute instance-attribute

    skip_tags: tuple[str, ...] = ()
    

    Tags to drop together with their content, e.g. ("script", "style").

    MarkdownifyConverter

    Bases: HtmlToMarkdownConverter

    markdownify: pure-Python converter on top of BeautifulSoup, highly configurable.

    Not supported: code_block_style="indented", code_fence="~~~", link_style="reference".

    Source code in src/mkconvert/converters/markdownify.py
    class MarkdownifyConverter(HtmlToMarkdownConverter):
        """markdownify: pure-Python converter on top of BeautifulSoup, highly configurable.
    
        Not supported: `code_block_style="indented"`, `code_fence="~~~"`,
        `link_style="reference"`.
        """
    
        name = "markdownify"
        requires = ("markdownify",)
        extra = "markdownify"
        supported_options: ClassVar[frozenset[str]] = frozenset({
            "heading_style",
            "bullet_marker",
            "emphasis_marker",
            "line_break",
            "skip_tags",
        })
    
        def __init__(
            self,
            options: HtmlToMarkdownOptions | None = None,
            *,
            on_unsupported: OnUnsupported = "warn",
            bullets: str | None = None,
            strip: Sequence[str] | None = None,
            convert: Sequence[str] | None = None,
            autolinks: bool = True,
            default_title: bool = False,
            code_language: str = "",
            code_language_callback: Callable[[Any], str | None] | None = None,
            escape_asterisks: bool = True,
            escape_underscores: bool = True,
            escape_misc: bool = False,
            sub_symbol: str = "",
            sup_symbol: str = "",
            table_infer_header: bool = False,
            wrap: bool = False,
            wrap_width: int = 80,
            strip_document: Literal["strip", "lstrip", "rstrip"] | None = "strip",
        ) -> None:
            """Create a markdownify converter.
    
            Args:
                options: Common options.
                on_unsupported: See `Backend`.
                bullets: Bullet markers per nesting level, e.g. `"*+-"`; overrides
                    `bullet_marker`.
                strip: Tags to drop while keeping their content.
                convert: Only convert these tags (keeping the text of all others).
                autolinks: `<https://...>` for links whose text is their URL.
                default_title: Use the URL as title of links without one.
                code_language: Language for fenced code blocks.
                code_language_callback: Derive the language from the `<pre>` element.
                escape_asterisks: Escape `*` in text.
                escape_underscores: Escape `_` in text.
                escape_misc: Escape other Markdown characters in text.
                sub_symbol: Wrap `<sub>` text in this symbol.
                sup_symbol: Wrap `<sup>` text in this symbol.
                table_infer_header: Use the first row as table header if there is no `<th>`.
                wrap: Wrap paragraphs at `wrap_width`.
                wrap_width: Line width for `wrap`.
                strip_document: Strip whitespace around the result.
            """
            super().__init__(options, on_unsupported=on_unsupported)
            from markdownify import MarkdownConverter
    
            o = self.options
            skip = frozenset(tag.lower() for tag in o.skip_tags)
    
            class _Converter(MarkdownConverter):
                def get_conv_fn(self, tag_name: str) -> Any:
                    if tag_name.lower() in skip:
                        return lambda *_args, **_kwargs: ""
                    return super().get_conv_fn(tag_name)  # ty: ignore[missing-attribute]
    
            self._converter = _Converter(
                heading_style="atx" if o.heading_style == "atx" else "underlined",
                bullets=bullets or o.bullet_marker,
                strong_em_symbol=o.emphasis_marker,
                newline_style=o.line_break,
                strip=list(strip) if strip is not None else None,
                convert=list(convert) if convert is not None else None,
                autolinks=autolinks,
                default_title=default_title,
                code_language=code_language,
                code_language_callback=code_language_callback,
                escape_asterisks=escape_asterisks,
                escape_underscores=escape_underscores,
                escape_misc=escape_misc,
                sub_symbol=sub_symbol,
                sup_symbol=sup_symbol,
                table_infer_header=table_infer_header,
                wrap=wrap,
                wrap_width=wrap_width,
                strip_document=strip_document,
            )
    
        def convert(self, text: str) -> str:
            """Convert HTML `text` to Markdown."""
            return self._converter.convert(text)
    

    __init__

    __init__(
        options: HtmlToMarkdownOptions | None = None,
        *,
        on_unsupported: OnUnsupported = "warn",
        bullets: str | None = None,
        strip: Sequence[str] | None = None,
        convert: Sequence[str] | None = None,
        autolinks: bool = True,
        default_title: bool = False,
        code_language: str = "",
        code_language_callback: Callable[[Any], str | None] | None = None,
        escape_asterisks: bool = True,
        escape_underscores: bool = True,
        escape_misc: bool = False,
        sub_symbol: str = "",
        sup_symbol: str = "",
        table_infer_header: bool = False,
        wrap: bool = False,
        wrap_width: int = 80,
        strip_document: Literal["strip", "lstrip", "rstrip"] | None = "strip",
    ) -> None
    

    Create a markdownify converter.

    Parameters:

    Name Type Description Default
    options HtmlToMarkdownOptions | None

    Common options.

    None
    on_unsupported OnUnsupported

    See Backend.

    'warn'
    bullets str | None

    Bullet markers per nesting level, e.g. "*+-"; overrides bullet_marker.

    None
    strip Sequence[str] | None

    Tags to drop while keeping their content.

    None
    convert Sequence[str] | None

    Only convert these tags (keeping the text of all others).

    None
    autolinks bool

    <https://...> for links whose text is their URL.

    True
    default_title bool

    Use the URL as title of links without one.

    False
    code_language str

    Language for fenced code blocks.

    ''
    code_language_callback Callable[[Any], str | None] | None

    Derive the language from the <pre> element.

    None
    escape_asterisks bool

    Escape * in text.

    True
    escape_underscores bool

    Escape _ in text.

    True
    escape_misc bool

    Escape other Markdown characters in text.

    False
    sub_symbol str

    Wrap <sub> text in this symbol.

    ''
    sup_symbol str

    Wrap <sup> text in this symbol.

    ''
    table_infer_header bool

    Use the first row as table header if there is no <th>.

    False
    wrap bool

    Wrap paragraphs at wrap_width.

    False
    wrap_width int

    Line width for wrap.

    80
    strip_document Literal['strip', 'lstrip', 'rstrip'] | None

    Strip whitespace around the result.

    'strip'
    Source code in src/mkconvert/converters/markdownify.py
    def __init__(
        self,
        options: HtmlToMarkdownOptions | None = None,
        *,
        on_unsupported: OnUnsupported = "warn",
        bullets: str | None = None,
        strip: Sequence[str] | None = None,
        convert: Sequence[str] | None = None,
        autolinks: bool = True,
        default_title: bool = False,
        code_language: str = "",
        code_language_callback: Callable[[Any], str | None] | None = None,
        escape_asterisks: bool = True,
        escape_underscores: bool = True,
        escape_misc: bool = False,
        sub_symbol: str = "",
        sup_symbol: str = "",
        table_infer_header: bool = False,
        wrap: bool = False,
        wrap_width: int = 80,
        strip_document: Literal["strip", "lstrip", "rstrip"] | None = "strip",
    ) -> None:
        """Create a markdownify converter.
    
        Args:
            options: Common options.
            on_unsupported: See `Backend`.
            bullets: Bullet markers per nesting level, e.g. `"*+-"`; overrides
                `bullet_marker`.
            strip: Tags to drop while keeping their content.
            convert: Only convert these tags (keeping the text of all others).
            autolinks: `<https://...>` for links whose text is their URL.
            default_title: Use the URL as title of links without one.
            code_language: Language for fenced code blocks.
            code_language_callback: Derive the language from the `<pre>` element.
            escape_asterisks: Escape `*` in text.
            escape_underscores: Escape `_` in text.
            escape_misc: Escape other Markdown characters in text.
            sub_symbol: Wrap `<sub>` text in this symbol.
            sup_symbol: Wrap `<sup>` text in this symbol.
            table_infer_header: Use the first row as table header if there is no `<th>`.
            wrap: Wrap paragraphs at `wrap_width`.
            wrap_width: Line width for `wrap`.
            strip_document: Strip whitespace around the result.
        """
        super().__init__(options, on_unsupported=on_unsupported)
        from markdownify import MarkdownConverter
    
        o = self.options
        skip = frozenset(tag.lower() for tag in o.skip_tags)
    
        class _Converter(MarkdownConverter):
            def get_conv_fn(self, tag_name: str) -> Any:
                if tag_name.lower() in skip:
                    return lambda *_args, **_kwargs: ""
                return super().get_conv_fn(tag_name)  # ty: ignore[missing-attribute]
    
        self._converter = _Converter(
            heading_style="atx" if o.heading_style == "atx" else "underlined",
            bullets=bullets or o.bullet_marker,
            strong_em_symbol=o.emphasis_marker,
            newline_style=o.line_break,
            strip=list(strip) if strip is not None else None,
            convert=list(convert) if convert is not None else None,
            autolinks=autolinks,
            default_title=default_title,
            code_language=code_language,
            code_language_callback=code_language_callback,
            escape_asterisks=escape_asterisks,
            escape_underscores=escape_underscores,
            escape_misc=escape_misc,
            sub_symbol=sub_symbol,
            sup_symbol=sup_symbol,
            table_infer_header=table_infer_header,
            wrap=wrap,
            wrap_width=wrap_width,
            strip_document=strip_document,
        )
    

    convert

    convert(text: str) -> str
    

    Convert HTML text to Markdown.

    Source code in src/mkconvert/converters/markdownify.py
    def convert(self, text: str) -> str:
        """Convert HTML `text` to Markdown."""
        return self._converter.convert(text)