Python parser for the CommonMark Markdown spec
npx @tessl/cli install tessl/pypi-commonmark@0.9.0A Python parser for the CommonMark Markdown spec that converts Markdown text into HTML and other formats. CommonMark provides a complete implementation of the CommonMark specification with both high-level convenience functions and low-level parsing/rendering control.
pip install commonmarkimport commonmarkFor specific components:
from commonmark import commonmark, Parser, HtmlRenderer, ReStructuredTextRenderer
from commonmark import dumpAST, dumpJSONimport commonmark
# Convert Markdown to HTML (default)
html = commonmark.commonmark("# Hello\n*World*!")
print(html) # <h1>Hello</h1>\n<p><em>World</em>!</p>\n
# Convert to other formats
json_ast = commonmark.commonmark("# Hello\n*World*!", format="json")
rst = commonmark.commonmark("# Hello\n*World*!", format="rst")from commonmark import Parser, HtmlRenderer
# Parse Markdown into AST
parser = Parser()
ast = parser.parse("# Hello\n*World*!")
# Render AST to HTML
renderer = HtmlRenderer()
html = renderer.render(ast)
print(html)CommonMark follows a two-stage processing model:
This design enables parsing once and rendering to multiple formats, as well as programmatic modification of the document structure.
Simple one-function interface for common Markdown conversion tasks, supporting multiple output formats with sensible defaults.
def commonmark(text, format="html"):
"""
Render CommonMark into HTML, JSON, AST, or reStructuredText.
Args:
text (str): CommonMark Markdown text to parse
format (str): Output format - 'html', 'json', 'ast', or 'rst'
Returns:
str: Rendered output in specified format
"""Comprehensive parsing functionality with full control over the Abstract Syntax Tree, including node creation, modification, and traversal operations.
class Parser:
def __init__(self, options={}): ...
def parse(self, my_input): ...
class Node:
def __init__(self, node_type, sourcepos): ...
def walker(self): ...
def append_child(self, child): ...
def unlink(self): ...
class NodeWalker:
def __init__(self, root): ...
def nxt(self): ...Multiple output format renderers with customizable options for converting AST to HTML, reStructuredText, and other formats.
class HtmlRenderer:
def __init__(self, options={}): ...
def render(self, ast): ...
class ReStructuredTextRenderer:
def __init__(self, indent_char=' '): ...
def render(self, ast): ...
class Renderer:
def render(self, ast): ...
def lit(self, s): ...
def cr(self): ...Utility functions for debugging, AST inspection, and format conversion including JSON serialization and pretty-printing.
def dumpAST(obj, ind=0, topnode=False): ...
def dumpJSON(obj): ...
def is_container(node): ...Command-line tool for processing Markdown files with support for various output formats and file I/O operations.
def main(): ...Available as cmark console command.