markdown-katex
markdown-katex is an extension for Python Markdown that adds KaTeX support. It processes LaTeX math formulas within Markdown text and converts them into HTML that can be rendered by KaTeX, often including bundled KaTeX binaries for server-side rendering, thus reducing reliance on client-side JavaScript. It primarily supports GitLab-style math delimiters. The current version is 202406.1035, with a release cadence that often aligns with KaTeX binary updates and bug fixes.
Warnings
- gotcha The `markdown-katex` extension specifically supports GitLab-style math delimiters: $`...`$ for inline math and ````math...```` for display math. Other common LaTeX delimiters like `$...$` or `$$...$$` will *not* be processed as math by this extension and will often be rendered as plain text or Markdown emphasis.
- gotcha Markdown processors can interfere with LaTeX syntax. Characters like underscores (`_`), asterisks (`*`), or backslashes (`\`) within LaTeX math formulas might be interpreted by Python Markdown (e.g., as emphasis) before `markdown-katex` can process them, leading to incorrect rendering.
- gotcha For KaTeX to render correctly in the browser, the generated HTML must include the KaTeX CSS stylesheet, typically from a CDN or a local copy. Additionally, the HTML document *must* start with `<!DOCTYPE html>` to prevent browsers from rendering in 'quirks mode,' which can cause display issues.
- gotcha The `markdown-katex` extension bundles KaTeX binaries for server-side rendering, but it will prioritize using a globally installed `katex-cli` if found on the system. This can lead to unexpected behavior or version mismatches if your system's `katex-cli` is older or configured differently than the version bundled with the Python package.
Install
-
pip install markdown-katex
Imports
- KatexExtension
from markdown_katex import KatexExtension
Quickstart
import markdown
from markdown_katex import KatexExtension
markdown_text = '''
# My Document with Math
Inline math: $`E=mc^2`$
Display math:
```math
x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}
```
'''
md = markdown.Markdown(extensions=[KatexExtension()])
html = md.convert(markdown_text)
print(html)
# For complete rendering, remember to include KaTeX CSS in your HTML:
# <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.css" integrity="sha384-wcNdUgu4o+9NqyZ/lXkP5b/SjP/0XfC/vS+G0Hh0Q0Q=" crossorigin="anonymous">