Sphinx Markdown Mermaid Preprocessor

Last year, we migrated all our companies documentation to markdown rendered via sphinx. Because of Gitlab and typora we are a little bit spoiled and wanted to keep our good looking mermaid js graphs - needles to say, that this was not supported by sphinx.

Our solution to that was to use a (hacky) pre- and a postprocessing script in the continuous integration.

The script goes through any markdown file and translates the markdown mermaid notation to a simple HTML mermaid notation.

from pathlib import Path

def mermaid(md):
    new_content = ""
    replacement_in_progress = False
    with open (md, 'r' ) as f:
        line = f.readline()
        while line:
            new_line = line
            if "```mermaid" in line:
                new_line = '<div class="mermaid">\n'
                replacement_in_progress = True
            elif "```" in line and replacement_in_progress:
                new_line = '</div>\n'
                replacement_in_progress = False
            new_content += new_line
            line = f.readline()
    with open (md, 'w' ) as f:

for md in Path("source").glob("**/*.md"):
    file_string = str(md.absolute())

The script can be used before the regular sphinx call of your continuous integration. Be aware, the inclusion of mermaid js has to be done in the used template, e.g. by adding the following lines to the conf.py

html_js_files = ['mermaid.min.js']
html_css_files = ['mermaid.css']

⚠ The source of the markdown files will be changed permanently, so please use this only in context of disposable (CI) environments.