---
title: Parsing and rewriting
description: Parse `md` and MediaWiki into immutable semantic `Document` trees, inspect
  source spans, and rewrite markup selectively.
order: 1
---
[`parse_md`](parse.md#parse_md) and [`parse_wiki`](parse.md#parse_wiki) return a shared immutable [`Document`](parse.md#document) consumed by every exporter ([`mdhtml2html`](export.md#mdhtml2html), [`mdhtml2gfm`](md.md#mdhtml2gfm), [`mdhtml2typst`](typst.md#mdhtml2typst), [`mdhtml2pdf`](typst.md#mdhtml2pdf)). Direct helpers ([`md2mdhtml`](parse.md#md2mdhtml), [`mdhtml2md`](parse.md#mdhtml2md), [`md2dom`](parse.md#md2dom), [`wrap_md`](parse.md#wrap_md)) convert strings or mutable `fast5ever` DOMs without managing a [`Document`](parse.md#document) manually.

```python
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`](parse.md#wrap_md) widths, or unknown [`rewrite`](parse.md#rewrite) field keys raise `ValueError`; invalid `templates` items or [`rewrite`](parse.md#rewrite) callback return types raise `TypeError`.

## Semantic documents

Use [`parse_md`](parse.md#parse_md) for `md` source, [`parse_wiki`](parse.md#parse_wiki) for MediaWiki source, and [`import_mdhtml`](export.md#import_mdhtml) (in [`mdhtml.export`](export.md)) to import an existing MDHTML string into a [`Document`](parse.md#document).

### parse\_md

```python
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`](parse.md#document), normalizing embedded HTML as a complete fragment.*

### parse\_wiki

```python
def parse_wiki(
    wikitext
):
```

*Parse MediaWiki `wikitext` into an immutable semantic [`Document`](parse.md#document).*

### Document

```python
class Document:
```

*Immutable semantic document parsed from `md`, MediaWiki, or MDHTML, shared by all exporters.*

#### Document.from\_mdhtml

```python
def from_mdhtml(
    mdhtml, frontmatter:str='', warnings=None
):
```

*Parse canonical `mdhtml` into a [`Document`](parse.md#document), attaching optional `frontmatter` and `warnings`.*

#### Document.map\_urls

```python
def map_urls(
    rewrite
):
```

*Return a copy with URLs rewritten by `rewrite(url, is_image)` (return `None` to keep a URL unchanged).*

#### Document.index

```python
def index(
    reftypes=None, number_headings=None, cite_style=None
):
```

*Build a [`ReferenceIndex`](export.md#referenceindex) for this document without mutating or baking it.*

#### Document.prepare

```python
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

```python
def bake(
    reftypes=None, number_headings=None, refs:str='resolve', links:bool=True, cite_style=None
):
```

*Return a new [`Document`](parse.md#document) with cross-references, numbering, captions, and citations resolved in place (`refs` is `'resolve'`, `'ids'`, or `'lenient'`).*

#### Document.mdhtml

```python
def mdhtml(
    callbacks=None
):
```

*Render this document to canonical MDHTML, optionally transforming nodes through `callbacks` keyed by node type.*

#### Document.markdown

```python
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

```python
@property
def blocks(self):
```

*Top-level semantic block dicts in document order.*

#### Document.footnotes

```python
@property
def footnotes(self):
```

*Mapping of footnote label to list of parsed block dicts.*

#### Document.meta

```python
@property
def meta(self):
```

*Leading frontmatter key/value metadata dict.*

#### Document.warnings

```python
@property
def warnings(self):
```

*Parse and resolution warning messages collected for this document.*

#### Document.frontmatter

```python
@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`](parse.md#mdhtml)), normalized `md`, or a mutable `fast5ever` DOM.

### md2mdhtml

```python
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`](parse.md#mdhtml) fragment.*

### Mdhtml

```python
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

```python
def meta()->MappingProxyType:
```

*Read-only frontmatter key/value metadata derived from `.frontmatter`.*

### mdhtml2md

```python
def mdhtml2md(
    src:str | Document | Node
)->str:
```

*Serialize MDHTML or a [`Document`](parse.md#document) to normalized `md` dialect source, retaining attached frontmatter.*

### wiki2mdhtml

```python
def wiki2mdhtml(
    wikitext:str
)->Mdhtml:
```

*Render MediaWiki source to canonical MDHTML, preserving expansion-dependent constructs as semantic instructions or raw wikitext.*

### md2dom

```python
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`](parse.md#md2mdhtml) to retain frontmatter.*

### parse\_fragment

```python
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`](parse.md#document) node holding the fragment's nodes.*

### wrap\_md

```python
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`](parse.md#blocks) and [`inlines`](parse.md#inlines), edit `md` source selectively via [`rewrite`](parse.md#rewrite), transform prose with [`replacements`](parse.md#replacements), configure inert template recognition via [`TemplateDelimiter`](parse.md#templatedelimiter), or walk semantic `data-op` nodes with [`ops`](parse.md#ops).

### blocks

```python
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

```python
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

```python
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

```python
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

```python
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

```python
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

```python
def split_frontmatter(
    src
):
```

*Split leading YAML frontmatter from `src`, returning `(payload, body)` with normalized `\n` line endings.*

### highlight\_md

```python
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.*
