CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-myst-parser

An extended CommonMark compliant parser, with bridges to docutils and Sphinx

Pending
Overview
Eval results
Files

sphinx-extension.mddocs/

Sphinx Extension

Complete Sphinx extension providing MyST markdown support with setup functions, custom directives, roles, reference resolution, and seamless integration with Sphinx's documentation system.

Capabilities

Extension Setup

Core setup functions for initializing MyST-Parser as a Sphinx extension, configuring the parsing environment, and integrating with Sphinx's build system.

def setup(app) -> dict:
    """
    Initialize the Sphinx extension.
    
    Main entry point called by Sphinx when loading the extension.
    Sets up MyST parser, configuration, and returns extension metadata.
    
    Args:
        app: Sphinx application instance
        
    Returns:
        Extension metadata dictionary with version and compatibility info
    """

def setup_sphinx(app, load_parser: bool = False) -> None:
    """
    Initialize all MyST settings and transforms in Sphinx.
    
    Comprehensive setup function that configures MyST parser integration,
    registers configuration values, adds transforms, and sets up event handlers.
    
    Args:
        app: Sphinx application instance
        load_parser: Whether to load the MyST parser immediately
    """

def create_myst_config(app) -> MdParserConfig:
    """
    Create MyST config object for Sphinx environment.
    
    Extracts MyST configuration from Sphinx configuration and creates
    a MdParserConfig instance with appropriate settings.
    
    Args:
        app: Sphinx application instance
        
    Returns:
        Configured MdParserConfig instance
    """

Usage example:

# In Sphinx conf.py
extensions = ['myst_parser']

# MyST configuration options
myst_enable_extensions = [
    "deflist",
    "tasklist", 
    "substitution",
    "colon_fence",
    "linkify",
    "replacements",
    "smartquotes"
]

myst_heading_anchors = 3
myst_footnote_transition = True
myst_dmath_double_inline = True

# Programmatic setup (for custom extensions)
from myst_parser.sphinx_ext.main import setup_sphinx, create_myst_config

def custom_setup(app):
    # Initialize MyST extension
    setup_sphinx(app, load_parser=True)
    
    # Get MyST configuration
    myst_config = create_myst_config(app)
    print(f"MyST extensions: {myst_config.enable_extensions}")
    
    return {"version": "1.0", "parallel_read_safe": True}

Custom Directives

MyST-specific Sphinx directives providing enhanced functionality for technical documentation, including figure handling and substitution references.

class FigureMarkdown(SphinxDirective):
    """
    Figure directive implementation for MyST markdown.
    
    Provides figure functionality specifically designed for MyST markdown
    with support for MyST-specific options and formatting.
    """
    
    has_content = True
    required_arguments = 1
    optional_arguments = 0
    final_argument_whitespace = True
    option_spec = {
        'alt': str,
        'height': str,
        'width': str,
        'scale': int,
        'align': lambda x: x,  # Validated by align function
        'target': str,
        'class': str,
        'name': str
    }
    
    def run(self) -> list: ...

def align(argument: str) -> str:
    """
    Validate alignment option for figure directives.
    
    Args:
        argument: Alignment value to validate
        
    Returns:
        Validated alignment value
        
    Raises:
        ValueError: When alignment value is invalid
    """

def figwidth_value(argument: str) -> str:
    """
    Validate figure width values.
    
    Args:
        argument: Width value to validate
        
    Returns:
        Validated width value
        
    Raises:
        ValueError: When width value is invalid
    """

Usage example:

# In MyST markdown document:
"""
:::{figure} path/to/image.png
:alt: Alternative text
:width: 80%
:align: center
:name: my-figure

Figure caption goes here.
:::

Reference the figure: {numref}`my-figure`
"""

# Programmatic directive usage
from myst_parser.sphinx_ext.directives import FigureMarkdown, align, figwidth_value

# Validate directive options
try:
    alignment = align("center")  # Valid: "left", "center", "right"
    width = figwidth_value("80%")  # Valid: percentage or length
    print(f"Alignment: {alignment}, Width: {width}")
except ValueError as e:
    print(f"Validation error: {e}")

Custom Roles

MyST-specific Sphinx roles for enhanced text processing and cross-referencing capabilities.

class SubstitutionReferenceRole(SphinxRole):
    """
    Role for substitution references in MyST markdown.
    
    Handles substitution reference syntax and provides integration
    with Sphinx's substitution system.
    """
    
    def run(self) -> tuple[list, list]: ...

Usage example:

# In MyST markdown with substitutions:
"""
---
myst:
  substitutions:
    project_name: "MyST-Parser"
    version: "4.0.1"
---

# {sub-ref}`project_name` Documentation

Version: {sub-ref}`version`
"""

# In conf.py for global substitutions:
myst_substitutions = {
    "project_name": "MyST-Parser",
    "version": "4.0.1",
    "author": "Chris Sewell"
}

Reference Resolution

Advanced reference resolution system for MyST cross-references, providing integration with Sphinx's reference system and support for MyST-specific reference formats.

class MystReferenceResolver:
    """
    Resolver for MyST reference syntax.
    
    Handles resolution of MyST-style references including:
    - Cross-references to sections, figures, tables
    - External references and inventory links
    - Custom domain references
    """
    
    def __init__(self, document): ...
    
    def resolve_reference(
        self, 
        ref_node, 
        has_explicit_title: bool, 
        title: str, 
        target: str
    ) -> tuple[str, str] | None: ...
    
    def resolve_any_xref(
        self,
        ref_node,
        has_explicit_title: bool,
        title: str,
        target: str
    ) -> list[tuple[str, str]]: ...

Usage example:

# MyST reference syntax examples:
"""
# Section Header {#my-section}

See {ref}`my-section` for details.

Cross-document reference: {doc}`other-document`

External reference: {external+sphinx:doc}`configuration`

Custom domain: {py:class}`MyClass`
"""

# Programmatic reference resolution
from myst_parser.sphinx_ext.myst_refs import MystReferenceResolver
from docutils import nodes

# Create resolver
resolver = MystReferenceResolver(document)

# Create reference node
ref_node = nodes.reference('', '', refuri='#my-section')

# Resolve reference
result = resolver.resolve_reference(
    ref_node, 
    has_explicit_title=False,
    title="Section Header",
    target="my-section"
)

if result:
    resolved_title, resolved_uri = result
    print(f"Resolved: {resolved_title} -> {resolved_uri}")

Math Configuration

MyST-Parser provides built-in support for mathematical expressions through markdown-it-py plugins and standard Sphinx math extensions. Configuration is handled through MyST settings.

Usage example:

# MyST math syntax:
"""
Inline math: $x^2 + y^2 = z^2$

Display math:
$$
\\int_{-\\infty}^{\\infty} e^{-x^2} dx = \\sqrt{\\pi}
$$

Math directive:
```{math}
:label: euler-formula

e^{i\\pi} + 1 = 0

Reference equation: {eq}euler-formula """

Configuration in conf.py:

myst_dmath_allow_labels = True myst_dmath_allow_space = True myst_dmath_allow_digits = True myst_dmath_double_inline = True

## Configuration Options

MyST-specific Sphinx configuration options:

```python
# In conf.py - Core MyST options
myst_enable_extensions = [
    "amsmath",      # LaTeX math environments
    "colon_fence",  # ::: fence syntax
    "deflist",      # Definition lists
    "dollarmath",   # $ and $$ math
    "fieldlist",    # Field lists
    "html_admonition", # HTML admonitions
    "html_image",   # HTML images
    "linkify",      # Auto-link URLs
    "replacements", # Text replacements
    "smartquotes",  # Smart quotes
    "strikethrough", # ~~text~~
    "substitution", # Text substitutions
    "tasklist",     # - [ ] task lists
]

# Heading configuration
myst_heading_anchors = 3
myst_heading_slug_func = None

# Link configuration
myst_all_links_external = False
myst_url_schemes = ("http", "https", "mailto", "ftp")

# Reference configuration
myst_ref_domains = None

# Math configuration
myst_dmath_allow_labels = True
myst_dmath_allow_space = True
myst_dmath_allow_digits = True
myst_dmath_double_inline = False

# HTML configuration
myst_html_meta = {}

# Footnote configuration
myst_footnote_transition = True
myst_footnote_sort = False

# Substitution configuration
myst_substitutions = {}

# Title configuration
myst_title_to_header = False

# Fence configuration
myst_fence_as_directive = []
myst_number_code_blocks = []

Types

Sphinx extension related type definitions:

class FigureMarkdown(SphinxDirective):
    """MyST figure directive implementation."""

class SubstitutionReferenceRole(SphinxRole):
    """MyST substitution reference role implementation."""

class MystReferenceResolver:
    """MyST reference resolution system."""

Install with Tessl CLI

npx tessl i tessl/pypi-myst-parser

docs

cli-tools.md

configuration.md

document-rendering.md

index.md

inventory-warnings.md

parsing.md

sphinx-extension.md

tile.json