Parsing and rewriting
Parse md and MediaWiki into immutable semantic Document trees, inspect source spans, and rewrite markup selectively.
parse_md and parse_wiki return a shared immutable Document consumed by every exporter (mdhtml2html, mdhtml2gfm, mdhtml2typst, mdhtml2pdf). Direct helpers (md2mdhtml, mdhtml2md, md2dom, wrap_md) convert strings or mutable fast5ever DOMs without managing a Document manually.
doc = parse_md("# Overview\n\nSee [@sec-setup].\n\n## Setup {#sec-setup}\n\nReady.")
assert not doc.warnings and "sec-setup" in doc.mdhtml()
rewritten = rewrite("Check [docs](old.md).", {"link": lambda n: {"url": n["url"].replace("old.md", "new.md")}})
assert rewritten == "Check [docs](new.md)."
Invalid option values, duplicate TemplateDelimiter.open strings, non-positive wrap_md widths, or unknown rewrite field keys raise ValueError; invalid templates items or rewrite callback return types raise TypeError.
Semantic documents
Use parse_md for md source, parse_wiki for MediaWiki source, and import_mdhtml (in mdhtml.export) to import an existing MDHTML string into a Document.
parse_md
def parse_md(
markdown:str, # Source text in the `md` dialect
*, math:MathMode='brackets', # Math syntax mode (`'brackets'`, `'dollars'`, or `'off'`)
bare_autolinks:bool=True, # Link bare `http://`/`https://` URLs in prose?
implicit_figures:bool=False, # Promote image-only paragraphs to `<figure>` elements?
frontmatter:bool=True, # Extract leading `---` YAML frontmatter?
templates:Iterable[TemplateDelimiter] | None=None, # Template delimiters to lower into inert `template` elements
max_block_depth:int | None=None, # Maximum nested container depth (`None` uses default limit)
max_link_paren_depth:int | None=None, # Maximum nested parenthesis depth in inline link URLs
)->Document: # Immutable semantic document
Parse md source into the shared semantic Document, normalizing embedded HTML as a complete fragment.
parse_wiki
def parse_wiki(
wikitext
):
Parse MediaWiki wikitext into an immutable semantic Document.
Document
class Document:
Immutable semantic document parsed from md, MediaWiki, or MDHTML, shared by all exporters.
Document.from_mdhtml
def from_mdhtml(
mdhtml, frontmatter:str='', warnings=None
):
Parse canonical mdhtml into a Document, attaching optional frontmatter and warnings.
Document.map_urls
def map_urls(
rewrite
):
Return a copy with URLs rewritten by rewrite(url, is_image) (return None to keep a URL unchanged).
Document.index
def index(
reftypes=None, number_headings=None, cite_style=None
):
Build a ReferenceIndex for this document without mutating or baking it.
Document.prepare
def prepare(
reftypes=None, number_headings=None, cite_style=None
):
Prepare numbers, citation text and bibliography layout; retain other references for native fields.
Document.bake
def bake(
reftypes=None, number_headings=None, refs:str='resolve', links:bool=True, cite_style=None
):
Return a new Document with cross-references, numbering, captions, and citations resolved in place (refs is 'resolve', 'ids', or 'lenient').
Document.mdhtml
def mdhtml(
callbacks=None
):
Render this document to canonical MDHTML, optionally transforming nodes through callbacks keyed by node type.
Document.markdown
def markdown(
gfm:bool=False, raw=None, tmpl=None
):
Serialize this document to md (or GitHub Markdown when gfm=True), passing through raw formats and rendering template operations via tmpl.
Document.blocks
@property
def blocks(self):
Top-level semantic block dicts in document order.
Document.footnotes
@property
def footnotes(self):
Mapping of footnote label to list of parsed block dicts.
Document.meta
@property
def meta(self):
Leading frontmatter key/value metadata dict.
Document.warnings
@property
def warnings(self):
Parse and resolution warning messages collected for this document.
Document.frontmatter
@property
def frontmatter(self):
Raw leading YAML frontmatter string, or '' when absent.
Direct conversions and DOM
Convert md or MediaWiki directly to canonical MDHTML (Mdhtml), normalized md, or a mutable fast5ever DOM.
md2mdhtml
def md2mdhtml(
markdown:str, # Source text in the `md` dialect
*, math:MathMode='brackets', # Math syntax mode (`'brackets'`, `'dollars'`, or `'off'`)
bare_autolinks:bool=True, # Link bare `http://`/`https://` URLs in prose?
implicit_figures:bool=False, # Promote image-only paragraphs to `<figure>` elements?
frontmatter:bool=True, # Extract leading `---` YAML frontmatter?
templates:Iterable[TemplateDelimiter] | None=None, # Template delimiters to recognize
callbacks:dict | None=None, # Render callbacks keyed by block/inline node type
max_block_depth:int | None=None, # Maximum nested container depth
max_link_paren_depth:int | None=None, # Maximum nested parenthesis depth in inline link URLs
)->Mdhtml: # Canonical MDHTML fragment carrying `.warnings`, `.frontmatter`, and `.meta`
Render md source to a canonical Mdhtml fragment.
Mdhtml
def Mdhtml(
s:str, warnings:list, frontmatter:str
):
An MDHTML fragment (str subclass) carrying .warnings, raw .frontmatter, and a read-only .meta mapping.
Mdhtml.meta
def meta()->MappingProxyType:
Read-only frontmatter key/value metadata derived from .frontmatter.
mdhtml2md
def mdhtml2md(
src:str | Document | Node
)->str:
Serialize MDHTML or a Document to normalized md dialect source, retaining attached frontmatter.
wiki2mdhtml
def wiki2mdhtml(
wikitext:str
)->Mdhtml:
Render MediaWiki source to canonical MDHTML, preserving expansion-dependent constructs as semantic instructions or raw wikitext.
md2dom
def md2dom(
markdown:str, # Source text in the `md` dialect
*, math:MathMode='brackets', # Math syntax mode (`'brackets'`, `'dollars'`, or `'off'`)
bare_autolinks:bool=True, # Link bare `http://`/`https://` URLs in prose?
implicit_figures:bool=False, # Promote image-only paragraphs to `<figure>` elements?
frontmatter:bool=True, # Extract leading `---` YAML frontmatter?
templates:Iterable[TemplateDelimiter] | None=None, # Template delimiters to recognize
callbacks:dict | None=None, # Render callbacks keyed by block/inline node type
max_block_depth:int | None=None, # Maximum nested container depth
max_link_paren_depth:int | None=None, # Maximum nested parenthesis depth in inline link URLs
)->Node: # Mutable `fast5ever` DOM `Document` for the rendered body
Render md source into a mutable fast5ever DOM; use md2mdhtml to retain frontmatter.
parse_fragment
def parse_fragment(
html, context:str='body'
):
Parse a fragment as the children of a context element (default body, matching innerHTML on ordinary content); returns the Document node holding the fragment's nodes.
wrap_md
def wrap_md(
markdown, width=None
):
Reflow markdown paragraphs to width columns without altering non-prose blocks; width=None unwraps paragraphs onto single lines.
Source spans and rewriting
Inspect parsed source offsets with blocks and inlines, edit md source selectively via rewrite, transform prose with replacements, configure inert template recognition via TemplateDelimiter, or walk semantic data-op nodes with ops.
blocks
def blocks(
markdown:str, # Source text in the `md` dialect
*, math:MathMode='brackets', # Math syntax mode (`'brackets'`, `'dollars'`, or `'off'`)
implicit_figures:bool=False, # Promote image-only paragraphs to figures?
templates:Iterable[TemplateDelimiter] | None=None, # Template delimiters to recognize
nested:bool=False, # Include blocks nested inside containers?
)->list[dict]: # Block span dicts with `type`, `start`, `end`, `depth`, and node fields
Report parsed block source spans, using the same figure and template-token promotion as rendering.
inlines
def inlines(
markdown:str, # Source text in the `md` dialect
*, math:MathMode='brackets', # Math syntax mode (`'brackets'`, `'dollars'`, or `'off'`)
bare_autolinks:bool=True, # Recognize bare URLs as links?
templates:Iterable[TemplateDelimiter] | None=None, # Template delimiters to recognize
)->list[dict]: # Inline span dicts in document order with character `start`/`end` offsets and `depth`
Report every inline construct and plain text run in document order with character offsets into markdown.
rewrite
def rewrite(
markdown:str, # Source text in the `md` dialect
callbacks:dict, # Mapping of block/inline node type to `cb(node) -> None | str | dict`
*, math:MathMode='brackets', # Math syntax mode (`'brackets'`, `'dollars'`, or `'off'`)
templates:Iterable[TemplateDelimiter] | None=None, # Template delimiters to recognize
implicit_figures:bool=False, # Promote image-only paragraphs to figures?
)->str: # Rewritten `md` source with untouched regions byte-identical
Rewrite block and inline nodes through callbacks keyed by node type, leaving untouched regions byte-identical.
Each callback receives the parsed node dict plus node['source']. Return None to keep it unchanged, a replacement string to replace the full span, or a field dict ({'url': ...} for inline link/image, {'tex': ...} for math_inline) to edit just that subspan.
replacements
def replacements(
*pairs:tuple[str, str]
):
Build a text render callback applying regex/replacement pairs to plain text, e.g. callbacks={'text': replacements(*DASHES)}.
TemplateDelimiter
def TemplateDelimiter(
syntax:str, # Syntax label recorded in `data-op` (e.g. `'mustache'`, `'jinja'`)
open:str, # Opening delimiter literal (e.g. `'{{'`)
close:str, # Closing delimiter literal (e.g. `'}}'`)
balance:tuple[str, str] | None=None, # Optional `(open_char, close_char)` pair to balance inside a token
form:"Literal['auto', 'inline', 'block']"='auto', # Placement rule (`'auto'`, `'inline'`, or `'block'`)
sigils:tuple[str, str, str] | None=None, # Optional `(open, inverted, close)` range sigils, e.g. `('#', '^', '/')`
)->None:
A template syntax lowered to semantic instructions in inert MDHTML template elements.
ops
def ops(
node:Node, # `fast5ever` DOM node to walk
syntax:str | None=None, # Optional syntax prefix filter (e.g. `'mustache'`)
inner_first:bool=False, # Yield nested inner operations before their enclosing operation?
)->list[Element]: # Matching `data-op` elements, including those inside `<template>` contents
Collect semantic data-op elements from a fast5ever DOM, descending into inert <template> contents.
Helpers
split_frontmatter
def split_frontmatter(
src
):
Split leading YAML frontmatter from src, returning (payload, body) with normalized \n line endings.
highlight_md
def highlight_md(
src, class_prefix:str='hl-'
):
Return classed-span inner HTML highlighting src as the md dialect itself, matching hl='spans' theme scopes.