API Reference
CLI
CLI tool for extracting and rendering Mermaid diagrams from Markdown files.
Extractors
Extractor functions for parsing content from Markdown files.
- markdown_diagrams.extractors.heading_to_filename(heading: str) str[source]
Convert a markdown heading to a filesystem-safe filename stem.
- Parameters:
heading – Raw heading text (e.g.
3.1 System Architecture).- Returns:
A lowercase, underscore-separated filename stem (e.g.
system_architecture).
- markdown_diagrams.extractors.extract_diagrams(markdown_file: Path, diagram_types: List[str] = None) Dict[str, List[Dict[str, Any]]][source]
Extract diagrams from a Markdown file.
- Parameters:
markdown_file – Path to the Markdown file.
diagram_types – List of diagram types to extract. If None, extract all supported types.
- Returns:
content: The diagram source text.heading: The best available label for the diagram: a bold-text title immediately above the fence if present, otherwise the nearest preceding markdown heading, or None.
- Return type:
Dictionary mapping diagram type to a list of dicts, each with
- markdown_diagrams.extractors.extract_mermaid_diagrams(markdown_file: Path) List[str][source]
Extract Mermaid diagrams from a Markdown file (legacy function).
- Parameters:
markdown_file – Path to the Markdown file.
- Returns:
List of Mermaid diagram content strings.
- markdown_diagrams.extractors.extract_diagrams_with_position(markdown_file: Path, diagram_type: str = 'mermaid') List[Tuple[str, int, int]][source]
Extract diagrams along with their position in the file.
- Parameters:
markdown_file – Path to the Markdown file
diagram_type – Type of diagram to extract positions for
- Returns:
List of tuples containing (diagram_content, start_position, end_position)
Renderers
Mermaid Diagram Renderer
This module provides functionality to render Mermaid diagrams to various image formats, including PNG, SVG, and PDF.
- markdown_diagrams.renderers.sanitize_mermaid_content(content: str) str[source]
Public alias for
_sanitize_mermaid_content().Sanitize Mermaid diagram content to prevent common parse errors. See
_sanitize_mermaid_content()for full documentation.- Parameters:
content – Raw Mermaid diagram source.
- Returns:
Sanitized Mermaid source safe for rendering.
- markdown_diagrams.renderers.check_mermaid_cli() bool[source]
Check if Mermaid CLI is available.
- Returns:
True if Mermaid CLI (
mmdc) is found on$PATH.
- markdown_diagrams.renderers.render_mermaid_to_png(mermaid_content: str, output_path: str, width: int = 800, height: int = 600, theme: str = 'default') bool[source]
Render a Mermaid diagram to PNG format.
- Parameters:
mermaid_content (str) – The Mermaid diagram content
output_path (str) – Path where the PNG will be saved
width (int) – Width of the output image
height (int) – Height of the output image
theme (str) – Mermaid theme (‘default’, ‘dark’, ‘forest’)
- Returns:
True if successful, False otherwise
- Return type:
bool
- markdown_diagrams.renderers.render_mermaid_to_svg(mermaid_content: str, output_path: str, width: int = 800, height: int = 600, theme: str = 'default') bool[source]
Render a Mermaid diagram to SVG format.
- Parameters:
mermaid_content (str) – The Mermaid diagram content
output_path (str) – Path where the SVG will be saved
width (int) – Width of the output image
height (int) – Height of the output image
theme (str) – Mermaid theme (‘default’, ‘dark’, ‘forest’)
- Returns:
True if successful, False otherwise
- Return type:
bool
- markdown_diagrams.renderers.render_mermaid_to_pdf(mermaid_content: str, output_path: str, theme: str = 'default') bool[source]
Render a Mermaid diagram to PDF format.
- Parameters:
mermaid_content (str) – The Mermaid diagram content
output_path (str) – Path where the PDF will be saved
theme (str) – Mermaid theme (‘default’, ‘dark’, ‘forest’)
- Returns:
True if successful, False otherwise
- Return type:
bool
- markdown_diagrams.renderers.render_mermaid_diagram(mermaid_content: str, output_dir: str, format_type: str = 'png', width: int = 800, height: int = 600, theme: str = 'default', name: str | None = None) str | None[source]
Render a Mermaid diagram to the specified format.
- Parameters:
mermaid_content (str) – The Mermaid diagram content.
output_dir (str) – Directory where the output image will be saved.
format_type (str) – Output format (‘png’, ‘svg’, ‘pdf’).
width (int) – Width of the output image.
height (int) – Height of the output image.
theme (str) – Mermaid theme (‘default’, ‘dark’, ‘forest’).
name (str) – Optional filename stem. Falls back to a content hash.
- Returns:
Path to the rendered file or None if failed.
- Return type:
str
Validators
Mermaid Diagram Validator and Auto-fixer
Provides validation of Mermaid diagrams via the Mermaid CLI (mmdc) and heuristic auto-fixing of common syntax issues, with optional write-back of fixes to the source Markdown file.
- class markdown_diagrams.validators.ValidationResult(index: int, heading: str | None, content: str, valid: bool, errors: List[str] = <factory>, fixed_content: str | None = None, start: int = 0, end: int = 0)[source]
Bases:
objectResult of validating a single Mermaid diagram.
- index: int
1-based position of the diagram within the file.
- heading: str | None
Nearest preceding Markdown heading, or
None.
- content: str
Original diagram source text.
- valid: bool
Trueif mmdc accepted the diagram without errors.
- errors: List[str]
List of error messages returned by mmdc (empty when valid).
- fixed_content: str | None = None
Auto-fixed diagram source, or
Noneif no changes were needed.
- start: int = 0
Byte offset of the opening mermaid fence in the file.
- end: int = 0
Byte offset immediately after the closing fence.
- markdown_diagrams.validators.fix_diagram(content: str) str[source]
Apply heuristic fixes to Mermaid diagram content.
Fixes applied (in order):
Normalize line endings (
\r\nand bare\r→\n).Strip trailing whitespace from every line.
Strip leading and trailing blank lines.
Quote node labels and edge labels that contain parentheses in
flowchart/graphdiagrams (delegates tosanitize_mermaid_content()).
- Parameters:
content – Raw Mermaid diagram source.
- Returns:
Fixed Mermaid source. Returns the original string unchanged if no fixes were necessary.
- markdown_diagrams.validators.validate_diagram(content: str) Tuple[bool, List[str]][source]
Validate a Mermaid diagram by attempting to render it with mmdc.
Writes content to a temporary
.mmdfile, invokesmmdc -i <input> -o <output>in a temporary directory, and inspects the exit code and stderr to determine validity.If mmdc is not installed the function returns
(True, [])and logs a warning rather than treating every diagram as invalid.- Parameters:
content – Mermaid diagram source text.
- Returns:
A
(valid, errors)tuple where valid isTruewhen mmdc exits with code 0 and errors is a (possibly empty) list of error messages parsed from stderr.
- markdown_diagrams.validators.validate_and_fix_diagrams(markdown_file: Path, apply_fixes: bool = False) List[ValidationResult][source]
Validate all Mermaid diagrams in a Markdown file.
For each
```mermaidblock the function:validates the diagram with
validate_diagram(),computes a fixed version with
fix_diagram()(fixed_contentis set only when the fixed text differs from the original),optionally writes all fixes back to markdown_file in a single atomic pass (last-to-first to preserve byte offsets).
- Parameters:
markdown_file – Path to the source Markdown file.
apply_fixes – When
True, write fixed diagram content back to markdown_file for every diagram wherefix_diagram()produces a different result.
- Returns:
Ordered list of
ValidationResult, one per diagram found. Returns an empty list when no Mermaid diagrams are present or the file cannot be read.
Dependencies
External dependency checker for markdown-diagrams.
Verifies that required external tools (e.g. the Mermaid CLI) are installed
and reachable on $PATH, and provides platform-aware installation
instructions when they are not.
- class markdown_diagrams.dependencies.Dependency(name: str, command: str, version_flag: str = '--version', why: str = '', install_instructions: List[str] = <factory>, url: str = '')[source]
Bases:
objectDescription of a single external dependency.
- name: str
Human-readable name (e.g.
Mermaid CLI).
- command: str
Executable name to look up on
$PATH(e.g.mmdc).
- version_flag: str = '--version'
Flag passed to command to retrieve a version string.
- why: str = ''
Short explanation of why this dependency is needed.
- install_instructions: List[str]
Ordered list of installation methods. Each entry is a human-readable string that may contain a shell command (the caller is responsible for formatting).
- url: str = ''
Project homepage / documentation URL.
- markdown_diagrams.dependencies.ALL_DEPENDENCIES: List[Dependency] = [Dependency(name='Mermaid CLI (mmdc)', command='mmdc', version_flag='--version', why='Required to render Mermaid diagrams to PNG, SVG, and PDF.', install_instructions=['npm install -g @mermaid-js/mermaid-cli', 'yarn global add @mermaid-js/mermaid-cli', 'brew install mermaid-cli (macOS with Homebrew)'], url='https://github.com/mermaid-js/mermaid-cli')]
Every external tool that markdown-diagrams may need at runtime.
- class markdown_diagrams.dependencies.DependencyStatus(dependency: Dependency, available: bool, version: str | None = None)[source]
Bases:
objectResult of checking a single dependency.
- dependency: Dependency
- available: bool
- version: str | None = None
- markdown_diagrams.dependencies.check_dependency(dep: Dependency) DependencyStatus[source]
Check whether dep is installed and return its status.
- Parameters:
dep – The dependency to check.
- Returns:
A
DependencyStatusindicating availability and version.
- markdown_diagrams.dependencies.check_all() List[DependencyStatus][source]
Check every dependency in
ALL_DEPENDENCIES.- Returns:
List of
DependencyStatusobjects, one per dependency.
- markdown_diagrams.dependencies.format_missing_message(status: DependencyStatus) str[source]
Return a detailed, user-friendly error message for a missing dependency.
- Parameters:
status – A
DependencyStatuswhereavailableisFalse.- Returns:
Multi-line string with the problem description and install options.
- markdown_diagrams.dependencies.require_all(strict: bool = True) List[DependencyStatus][source]
Check all dependencies and optionally raise on missing ones.
- Parameters:
strict – If
True(the default), raiseSystemExitwhen any dependency is missing. IfFalse, just log warnings.- Returns:
List of
DependencyStatusobjects.- Raises:
SystemExit – When strict is
Trueand a dependency is missing.