Skip to main content

typsphinx

CI PyPI version Python Support License: MIT Code style: black Documentation Status

Sphinx extension for Typst output format support.

📖 Documentation | 🐛 Issue Tracker | 📦 PyPI

Overview

typsphinx is a Sphinx extension that enables generating Typst documents from reStructuredText sources. Typst is a modern typesetting system designed as an alternative to LaTeX, offering faster compilation and a more intuitive syntax.

Features

  • Convert Sphinx documentation to Typst format: Seamlessly transform your reStructuredText/Markdown documents
  • Standard docutils nodes: Full support for paragraphs, sections, lists, tables, admonitions, and more
  • Mathematical expressions:
    • LaTeX syntax via mitex (@preview/mitex:0.2.7)
    • Native Typst math syntax
  • Code blocks with syntax highlighting: Using codly package (@preview/codly:1.3.0)
    • Automatic line numbering
    • Syntax highlighting for multiple languages
    • Highlight specific lines
  • Images and figures: Embed images with captions and references
  • Cross-references: Maintain document structure with internal links
  • Customizable templates: Use default or custom Typst templates
  • Direct PDF generation: Self-contained PDF generation via typst-py (no external Typst CLI required)
  • Multi-document support: Generate multiple Typst files with toctree integration using #include()

Requirements

  • Python 3.12 or higher
  • Sphinx 9.1 or higher
  • typst-py 0.15.0 or higher

Installation

From PyPI

pip install typsphinx
# Clone the repository
git clone https://github.com/YuSabo90002/typsphinx.git
cd typsphinx

# Install dependencies with uv
uv sync

# For development dependencies
uv sync --extra dev

Quick Start

Basic Configuration

Configure Typst output in your conf.py:

# conf.py

# Note: typsphinx is auto-discovered via entry points.
# Adding to extensions list is optional but recommended for clarity.
# extensions = ['typsphinx']

# Optional: Configure Typst builder
typst_use_mitex = True  # Use mitex for LaTeX math (default: True)

typst_documents

typst_documents is the list of master documents to build. Each entry is a tuple (source, target, title, author, documentclass), and each entry produces a wrapper .typ file at the entry's target and, under the typstpdf builder, one compiled .pdf from that wrapper; the entry's source document is additionally emitted as its own .typ file holding the document body, as is every other document in the project. See docs/source/user_guide/output_layout.rst for the full contract and which file to compile.

You never need to set it for a single-master project — leaving it unset is supported, and that's exactly what this Quick Start does. When unset, typsphinx derives a single entry from root_doc, project, and author: the target stem is project run through the same filename helper Sphinx's own LaTeX builder uses, so project = "My Project" yields myproject.typ and, under typstpdf, myproject.pdf. This is more than a rename — the derived entry makes the root document a master, so its emitted .typ gains the full template wrapper it would not otherwise receive.

An explicit typst_documents value — including an explicit empty list [] — always overrides the derived default: Sphinx resolves your raw config value before falling back to the callable default.

Only the documents named in typst_documents (or the single derived entry) become PDFs. A document reached only through a toctree is not a separate PDF — it is emitted as its own .typ file and pulled into its master through Typst's #include().

Build Typst Output

# Generate Typst files
sphinx-build -b typst source build/typst

# Generate PDF directly
sphinx-build -b typstpdf source build/pdf

Example Document

Create a simple reStructuredText document:

==============
My Document
==============

This is a paragraph with **bold** and *italic* text.

Math Example
============

Inline math: :math:`E = mc^2`

Block math:

.. math::

   \int_{-\infty}^{\infty} e^{-x^2} dx = \sqrt{\pi}

Code Example
============

.. code-block:: python

   def hello_world():
       print("Hello, Typst!")

This will generate a Typst file with:

  • Proper heading hierarchy
  • Formatted text with emphasis
  • LaTeX math via mitex (or native Typst math)
  • Syntax-highlighted code blocks with codly

Advanced Usage

Custom Templates

Create a custom Typst template:

# conf.py
typst_template = '_typst/custom.typ'

Template Parameter Mapping

Map Sphinx metadata to template parameters:

# conf.py
typst_template_mapping = {
    'project': 'doc_title',
    'author': 'doc_authors',
    'release': 'version',
}

Keys are Sphinx metadata names; values are the template parameter names they map to.

Multi-Document Projects

Use toctree to combine multiple documents:

.. toctree::
   :maxdepth: 2
   :numbered:

   intro
   chapter1
   chapter2

This generates #include() directives in Typst with proper heading level adjustments.

Working with Third-Party Extensions

typsphinx integrates with Sphinx's standard extension mechanism. For custom nodes from third-party extensions (e.g., sphinxcontrib-mermaid), you can register Typst handlers in your conf.py:

# conf.py
def setup(app):
    # Example: Support sphinxcontrib-mermaid diagrams
    if 'sphinxcontrib.mermaid' in app.config.extensions:
        from sphinxcontrib.mermaid import mermaid
        from docutils import nodes

        def typst_visit_mermaid(self, node):
            """Render Mermaid diagram as image in Typst output"""
            # Export diagram as SVG and include in Typst
            diagram_path = f"diagrams/{node['name']}.svg"
            self.add_text(f'#image("{diagram_path}")\n\n')
            raise nodes.SkipNode

        # Register with Sphinx's standard API
        app.add_node(mermaid, typst=(typst_visit_mermaid, None))

How it works:

  • typsphinx uses Sphinx's standard app.add_node() API (no custom registry needed)
  • Unknown nodes trigger unknown_visit() which logs a warning and extracts text content
  • Users can add Typst support for any extension by registering handlers in conf.py

For more details, see the Sphinx Extension API documentation.

Configuration Options

Below are the main configuration options. This is not the complete set — see docs/source/user_guide/configuration.rst for the full reference:

  • typst_documents: Master documents to build, as [(source, target, title, author, documentclass), ...] — optional; when unset, typsphinx derives a single master from root_doc/project/author (target <project>.typ), and an explicit value always overrides that derived default. The target names the entry's wrapper file.
  • typst_use_mitex: Enable/disable mitex for LaTeX math
  • typst_template: Custom template path
  • typst_elements: Template parameters (paper size, fonts, etc.)
  • typst_template_mapping: Sphinx metadata to template parameter mapping

Development

This project uses uv for fast package management and follows TDD (Test-Driven Development) practices.

Setup Development Environment

# Install with development dependencies
uv sync --extra dev

# Run tests
uv run pytest

# Run tests with coverage report
uv run pytest --cov=typsphinx --cov-report=html

# Run tests across multiple Python versions
uv run tox

# Run specific tox environments
uv run tox -e lint          # Run linters (black, ruff)
uv run tox -e type          # Run type checking (mypy)
uv run tox -e py312         # Run tests on Python 3.12
uv run tox -e docs-html     # Build HTML documentation
uv run tox -e docs-pdf      # Build PDF documentation
uv run tox -e docs          # Build both HTML and PDF docs
uv run tox -e linkcheck     # Check external links and anchors (needs network; not run by plain tox)

Testing Strategy

  • Unit tests: Cover all major components
  • Integration tests: Full build process validation
  • Example projects: examples/basic/ and examples/advanced/

Project Structure

typsphinx/
├── typsphinx/              # Main package
│   ├── builder.py          # Typst builder
│   ├── writer.py           # Doctree writer
│   ├── translator.py       # Node translator
│   ├── template_engine.py  # Template processor
│   ├── pdf.py              # PDF generation
│   └── templates/          # Default templates
├── tests/                  # Test suite
├── docs/                   # Documentation
├── examples/               # Example projects
└── pyproject.toml          # Project configuration

Known Limitations

  • Bibliography: BibTeX integration not yet supported
  • Citations: reStructuredText citation directives are not yet supported

Documentation

📖 Full documentation is available at typsphinx.readthedocs.io

日本語ドキュメントは typsphinx.readthedocs.io/ja/latest/ にあります。

Quick links:

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Write tests for new features
  4. Ensure all tests pass: uv run pytest
  5. Submit a pull request

Development Guidelines

  • Follow TDD (Test-Driven Development)
  • Use black for code formatting
  • Follow Sphinx extension conventions
  • Add tests for all new features

License

MIT License - see LICENSE file for details.

Acknowledgments

Version History

See CHANGELOG.md for detailed version history.


Status: Stable (v0.9.7) - Production ready Python: 3.12+ | Sphinx: 9.1+ | Typst: 0.15+

Metadata

Release files for typsphinx 0.9.7

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for typsphinx 0.9.7
File Size Uploaded
typsphinx-0.9.7.tar.gz 861.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for typsphinx 0.9.7
File Interpreter ABI Platform
typsphinx-0.9.7-py3-none-any.whl Python 3 none any Details

Total release size: 1.1 MB

Release files / typsphinx-0.9.7.tar.gz

Download URL typsphinx-0.9.7.tar.gz
Size 861.6 kB
Tags Source
SHA-256 checksum
How to use checksums
d4e5fe0cb9a4dbf9dc70fd47c4ddb9e561cfbd42cb080883e0878852c87534c4
BLAKE2b-256 checksum
How to use checksums
612afda816043419f6544dd324ec4653e1117762fbdb7507c5bd7392b204c151
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 28, 2026.

Transparency log

Release files / typsphinx-0.9.7-py3-none-any.whl

Download URL typsphinx-0.9.7-py3-none-any.whl
Size 194.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
159ea4945963804509f535cdbbe2ad24eaa735fe214f01a83f761dfbe508a2d2
BLAKE2b-256 checksum
How to use checksums
cc55e149c9b141e32c3b6a7b125f2c6b21f1fdcaf0543152b6bb1f142fc74bf3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 28, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.9.7 This release

2 release files

0.9.6

2 release files

0.9.2

2 release files

0.9.0

2 release files

0.8.0

2 release files

0.7.1

2 release files

0.7.0

2 release files

0.6.5

2 release files

0.6.4

2 release files

0.6.3

2 release files

0.6.2

2 release files

0.6.1

2 release files

0.6.0

2 release files

0.5.0

2 release files

0.4.4

2 release files

0.4.3

2 release files

0.4.2

2 release files

0.4.1

2 release files

0.4.0

2 release files

0.3.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page