CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-myst-nb

A Jupyter Notebook Sphinx reader built on top of the MyST markdown parser.

Pending
Overview
Eval results
Files

docutils.mddocs/

Docutils Integration

Standalone docutils parser and renderer for direct notebook processing without Sphinx, enabling integration into custom documentation pipelines. This provides MyST-NB functionality outside of the Sphinx ecosystem.

Capabilities

Docutils Parser

Main parser class for processing notebooks in standalone docutils applications.

class Parser(MystParser):
    """
    Docutils parser for MyST notebooks.
    
    Extends MystParser to handle notebook content in docutils
    processing pipelines without requiring Sphinx.
    """
    
    def parse(self, inputstring: str, document: nodes.document) -> None:
        """
        Parse notebook content into docutils document tree.
        
        Parameters:
        - inputstring: str - Raw notebook or MyST content
        - document: nodes.document - Target docutils document
        """

Docutils Renderer

Renderer class specifically designed for docutils output formats.

class DocutilsNbRenderer(DocutilsRenderer, MditRenderMixin):
    """
    Docutils notebook renderer.
    
    Combines DocutilsRenderer capabilities with notebook-specific
    rendering via MditRenderMixin for standalone docutils processing.
    """
    
    def render_nb_cell_code(self, cell, **kwargs):
        """Render code cells for docutils output."""
        pass
        
    def render_nb_cell_markdown(self, cell, **kwargs):
        """Render markdown cells for docutils output."""
        pass

Docutils Application Container

Container class for managing docutils roles and directives in MyST-NB context.

class DocutilsApp:
    """
    Container for docutils roles and directives.
    
    Provides a Sphinx-like application interface for registering
    and managing MyST-NB extensions in docutils-only environments.
    """
    
    def add_role(self, name: str, role_func: Callable) -> None:
        """Register a docutils role."""
        pass
        
    def add_directive(self, name: str, directive_class: type) -> None:
        """Register a docutils directive."""
        pass

CLI Functions

HTML Generation

Generate HTML output from notebooks using docutils backend.

def cli_html(args: list[str] | None = None) -> None:
    """
    Generate HTML output from notebook using docutils.
    
    Parameters:
    - args: Optional command-line arguments for HTML generation
    
    Command-line interface for converting notebooks to HTML
    without requiring Sphinx installation.
    """

HTML5 Generation

Generate modern HTML5 output with enhanced features.

def cli_html5(args: list[str] | None = None) -> None:
    """
    Generate HTML5 output from notebook using docutils.
    
    Parameters:
    - args: Optional command-line arguments for HTML5 generation
    
    Produces HTML5 output with modern web standards and features.
    """

LaTeX Generation

Generate LaTeX output suitable for PDF compilation.

def cli_latex(args: list[str] | None = None) -> None:
    """
    Generate LaTeX output from notebook using docutils.
    
    Parameters:
    - args: Optional command-line arguments for LaTeX generation
    
    Converts notebook content to LaTeX format for academic
    and publication-quality document generation.
    """

XML Generation

Generate structured XML output for data processing.

def cli_xml(args: list[str] | None = None) -> None:
    """
    Generate XML output from notebook using docutils.
    
    Parameters:
    - args: Optional command-line arguments for XML generation
    
    Produces structured XML representation of notebook content
    suitable for further processing or data exchange.
    """

Debug Output

Generate pseudo-XML for debugging document structure.

def cli_pseudoxml(args: list[str] | None = None) -> None:
    """
    Generate pseudo-XML output for debugging document structure.
    
    Parameters:
    - args: Optional command-line arguments for pseudo-XML generation
    
    Creates human-readable pseudo-XML showing the internal
    document tree structure for debugging purposes.
    """

Usage Examples

Basic Docutils Processing

from myst_nb.docutils_ import Parser, DocutilsNbRenderer
from docutils.core import publish_parts
from myst_nb.core.config import NbParserConfig

# Setup parser and renderer
config = NbParserConfig()
parser = Parser(config=config)
renderer = DocutilsNbRenderer()

# Process notebook content
with open("notebook.md", "r") as f:
    content = f.read()

# Generate HTML using docutils
parts = publish_parts(
    content,
    parser=parser,
    writer_name="html5"
)

html_output = parts['html_body']
print(html_output)

Custom Docutils Pipeline

from myst_nb.docutils_ import Parser, DocutilsApp
from docutils import nodes
from docutils.parsers.rst import directives

# Create docutils application
app = DocutilsApp()

# Register custom directive
class CustomDirective(directives.Directive):
    def run(self):
        return [nodes.paragraph(text="Custom content")]

app.add_directive("custom", CustomDirective)

# Setup parser with custom app
parser = Parser(app=app)

# Process content with custom extensions
content = """
# My Notebook

```{custom}
print("Hello from MyST-NB!")

"""

Convert to various formats

from docutils.core import publish_string

Generate HTML

html = publish_string(content, parser=parser, writer_name="html5")

Generate LaTeX

latex = publish_string(content, parser=parser, writer_name="latex")

### Batch Document Processing

```python
import os
from pathlib import Path
from myst_nb.docutils_ import cli_html, cli_latex

def batch_convert_notebooks(input_dir, output_dir, format="html"):
    """Convert all notebooks in directory to specified format."""
    input_path = Path(input_dir)
    output_path = Path(output_dir)
    output_path.mkdir(exist_ok=True)
    
    # Find all notebook files
    for nb_file in input_path.glob("*.md"):
        output_file = output_path / f"{nb_file.stem}.{format}"
        
        # Convert based on format
        if format == "html":
            cli_html([str(nb_file), str(output_file)])
        elif format == "latex":
            cli_latex([str(nb_file), str(output_file)])
        
        print(f"Converted: {nb_file} -> {output_file}")

# Usage
batch_convert_notebooks("notebooks/", "output/html/", "html")
batch_convert_notebooks("notebooks/", "output/latex/", "latex")

Integration with Build Systems

import subprocess
from myst_nb.docutils_ import DocutilsApp, Parser

class NotebookProcessor:
    """Notebook processor for build systems."""
    
    def __init__(self, config):
        self.config = config
        self.app = DocutilsApp()
        self.parser = Parser(config=config, app=self.app)
    
    def process_file(self, input_file, output_file, format="html"):
        """Process single notebook file."""
        try:
            # Use CLI functions for processing
            if format == "html":
                from myst_nb.docutils_ import cli_html
                cli_html([input_file, output_file])
            elif format == "latex":
                from myst_nb.docutils_ import cli_latex
                cli_latex([input_file, output_file])
            
            return True
        except Exception as e:
            print(f"Error processing {input_file}: {e}")
            return False
    
    def process_directory(self, input_dir, output_dir, format="html"):
        """Process all notebooks in directory."""
        success_count = 0
        error_count = 0
        
        for nb_file in Path(input_dir).glob("*.md"):
            output_file = Path(output_dir) / f"{nb_file.stem}.{format}"
            
            if self.process_file(str(nb_file), str(output_file), format):
                success_count += 1
            else:
                error_count += 1
        
        print(f"Processed: {success_count} success, {error_count} errors")
        return success_count, error_count

# Usage in build script
from myst_nb.core.config import NbParserConfig

config = NbParserConfig(
    execution_mode="auto",
    remove_code_source=False
)

processor = NotebookProcessor(config)
processor.process_directory("src/", "build/html/", "html")

Custom Writer Integration

from docutils import writers, nodes
from myst_nb.docutils_ import Parser

class CustomWriter(writers.Writer):
    """Custom writer for specialized output format."""
    
    def __init__(self):
        writers.Writer.__init__(self)
        self.translator_class = CustomTranslator
    
    def translate(self):
        self.visitor = self.translator_class(self.document)
        self.document.walkabout(self.visitor)
        self.output = self.visitor.astext()

class CustomTranslator(nodes.NodeVisitor):
    """Custom translator for notebook elements."""
    
    def __init__(self, document):
        nodes.NodeVisitor.__init__(self, document)
        self.body = []
    
    def visit_paragraph(self, node):
        self.body.append('<p>')
    
    def depart_paragraph(self, node):
        self.body.append('</p>\n')
    
    def astext(self):
        return ''.join(self.body)

# Register and use custom writer
writers.register_writer('custom', CustomWriter)

# Process with custom writer
from docutils.core import publish_string

content = """
# My Notebook

This is a paragraph.

```{code-cell} python
print("Hello, World!")

"""

output = publish_string( content, parser=Parser(), writer_name='custom' )

The docutils integration provides complete MyST-NB functionality outside of Sphinx, enabling integration into custom documentation pipelines, build systems, and standalone processing workflows.

Install with Tessl CLI

npx tessl i tessl/pypi-myst-nb

docs

cli.md

configuration.md

docutils.md

execution.md

glue.md

index.md

reading-processing.md

rendering.md

sphinx-extension.md

tile.json