m2r2: Markdown and reStructuredText Converter
M2R2 is a Python library designed to convert Markdown files, including embedded reStructuredText (RST) markups, into a valid RST format. It is a actively maintained fork of the original `m2r` library, specifically addressing compatibility issues with Sphinx 3+ and newer Python versions. M2R2 also functions as a Sphinx extension, enabling developers to write documentation in Markdown directly within Sphinx projects. The current version is 0.3.4, with a focused release cadence primarily for maintenance and compatibility updates.
Common errors
-
ImportError: cannot import name 'ErrorString' from 'docutils.core'
cause This error typically occurs when using the older `m2r` library with a newer version of `docutils` (e.g., Docutils 0.19+), which removed `ErrorString` from `docutils.core`. M2R2 was updated to address this incompatibility.fixUninstall `m2r` and install `m2r2`: `pip uninstall m2r && pip install m2r2`. Ensure your Sphinx `conf.py` uses `'m2r2'` in `extensions`. -
WARNING: could not import extension m2r (exception: cannot import name 'ErrorString' from 'docutils.core')
cause Sphinx failed to load the `m2r` extension due to a breaking change in `docutils` where `ErrorString` was removed. This specifically points to using the outdated `m2r` with an incompatible `docutils` version.fixUpgrade to `m2r2` by running `pip uninstall m2r && pip install m2r2`. Also, update your Sphinx `conf.py` to use `extensions = ['m2r2']` instead of `'m2r'`.
Warnings
- breaking Version 0.3.3 dropped support for Python versions prior to 3.7. Ensure your environment uses Python 3.7 or newer to avoid compatibility issues.
- gotcha M2R2 is a fork of the unmaintained `m2r` library. Using `m2r` (the original) with newer Sphinx or Docutils versions can lead to `ImportError` or other compatibility issues. Always prefer `m2r2` for modern Python and Sphinx projects.
- gotcha When using `m2r2` as a Sphinx extension, ensure `sphinxcontrib.mermaid` is also in your `extensions` list if you intend to render Mermaid diagrams using the `.. mermaid::` directive, especially if `m2r_use_mermaid` is set to 'auto' (the default).
Install
-
pip install m2r2
Imports
- convert
import m2r
from m2r2 import convert
- parse_from_file
from m2r2 import parse_from_file
Quickstart
from m2r2 import convert
import os
# Programmatic conversion of a Markdown string
markdown_text = """# My Document\n\nThis is **Markdown** with `inline code` and also `reST :role:` content.\n\n.. admonition:: Note\n This is reStructuredText inside Markdown.\n"""
rst_output = convert(markdown_text)
print("--- Converted RST ---")
print(rst_output)
# Command-line usage (assuming 'my_document.md' exists)
# You can also run 'm2r2 my_document.md' from your terminal
# It will create 'my_document.rst'
# For Sphinx integration, add 'm2r2' to extensions in conf.py:
# extensions = [
# 'sphinx.ext.autodoc',
# 'm2r2',
# ]
# Then Sphinx will process .md files.