all2md.ast.builder

Builder helper classes for constructing AST structures.

This module provides helper classes that simplify the construction of complex AST structures like nested lists and tables. These builders handle the bookkeeping of nesting and structure, allowing parsers to focus on content extraction.

class all2md.ast.builder.ListBuilder

Bases: object

Helper for building nested list structures.

This class manages the complexity of creating properly nested lists, handling level transitions and list type changes automatically.

Parameters:
  • root (Document or None, default = None) – Root document to append lists to. If None, creates a new Document.

  • allow_placeholders (bool, default = False) – If True, allows creation of placeholder list items when nesting without a parent item. Placeholder items will be marked with metadata {“placeholder”: True}. If False, raises ValueError on invalid nesting.

  • default_start (int, default = 1) – Default starting number for ordered lists

  • default_tight (bool, default = True) – Default tight spacing for lists (True means no blank lines between items)

Examples

>>> builder = ListBuilder()
>>> builder.add_item(level=1, ordered=False, content=[Text("Item 1")])
>>> builder.add_item(level=2, ordered=False, content=[Text("Nested")])
>>> builder.add_item(level=1, ordered=False, content=[Text("Item 2")])
>>> doc = builder.get_document()

Initialize the list builder with an optional root document.

__init__(root: Document | None = None, allow_placeholders: bool = False, default_start: int = 1, default_tight: bool = True)

Initialize the list builder with an optional root document.

add_item(level: int, ordered: bool, content: list[Node], task_status: Literal['checked', 'unchecked'] | None = None, start: int | None = None, tight: bool | None = None) None

Add a list item at the specified nesting level.

Parameters:
  • level (int) – Nesting level (1 is top-level, 2 is nested once, etc.)

  • ordered (bool) – True for ordered lists, False for unordered

  • content (list of Node) – Block content for the list item

  • task_status ({'checked', 'unchecked'} or None, default = None) – Optional task list status

  • start (int or None, default = None) – Starting number for ordered lists. If None, uses default_start. Only applies when a new list is created.

  • tight (bool or None, default = None) – Tight spacing for lists. If None, uses default_tight. Only applies when a new list is created.

Raises:

ValueError – If level is less than 1, or if allow_placeholders=False and nesting is attempted without a parent item

get_document() Document

Get the constructed document.

Returns:

Document containing all built lists

Return type:

Document

class all2md.ast.builder.TableBuilder

Bases: object

Helper for building table structures.

This class simplifies table construction by handling row and cell management, alignment tracking, and header designation.

Parameters:

has_header (bool, default = False) – Whether the first row should be designated as a header

Examples

>>> builder = TableBuilder(has_header=True)
>>> builder.add_row([Text("Name"), Text("Age")], is_header=True)
>>> builder.add_row([Text("Alice"), Text("30")])
>>> builder.add_row([Text("Bob"), Text("25")])
>>> table = builder.get_table()

Initialize the table builder with optional header flag.

__init__(has_header: bool = False)

Initialize the table builder with optional header flag.

add_row(cells: Sequence[str | Node | Sequence[Node]], is_header: bool = False, alignments: list[Literal['left', 'center', 'right'] | None] | None = None) None

Add a row to the table.

This method accepts a flexible cell specification allowing mixed types per cell. Each cell can be a plain string, a single Node, or a sequence of inline Node objects.

Parameters:
  • cells (Sequence of str, Node, or Sequence of Node) –

    Cell contents where each cell can be: - A plain string (e.g., “Hello”) - A single Node (e.g., Text(“Hello”)) - A sequence of inline nodes (e.g., [Text(“Hello”), Strong(content=[Text(“world”)])])

    Mixed types are supported per-cell. An empty sequence creates an empty row.

  • is_header (bool, default False) – Whether this is a header row. If has_header=True and no header exists yet, the first row added will automatically be treated as a header regardless of this parameter.

  • alignments (list of Alignment or None, optional) – Column alignments (only used for header rows). Length should match the number of cells. If not specified and this is a header row, all alignments will be set to None (default alignment).

Examples

[“Name”, “Age”] # All strings [Text(“Name”), Text(“Age”)] # All single nodes [[Text(“Name”)], [Text(“Age”)]] # All node sequences [“Name”, [Text(“Age: “), Strong(content=[Text(“30”)])]] # Mixed [Text(“Name”), [Text(“Age: “), Strong(content=[Text(“30”)])]] # Mixed

Notes

The flexible typing allows for ergonomic table building while maintaining type safety. The implementation normalizes all inputs to TableCell objects internally.

set_caption(caption: str) None

Set the table caption.

Parameters:

caption (str) – Table caption text

set_column_alignment(column_index: int, alignment: Literal['left', 'center', 'right'] | None) None

Set alignment for a specific column.

Parameters:
  • column_index (int) – Zero-based column index

  • alignment ({'left', 'center', 'right'} or None) – Column alignment

get_table() Table

Get the constructed table.

Returns:

Completed table node

Return type:

Table

class all2md.ast.builder.DocumentBuilder

Bases: object

Helper for building complete documents.

This class provides a fluent interface for constructing documents with multiple block-level elements. It supports method chaining for ergonomic document construction.

Examples

Basic usage with headings and paragraphs:

>>> builder = DocumentBuilder()
>>> builder.add_heading(1, [Text("Title")])
>>> builder.add_paragraph([Text("Content")])
>>> doc = builder.get_document()

Using method chaining:

>>> doc = (DocumentBuilder()
...     .add_heading(1, [Text("My Document")])
...     .add_paragraph([Text("Introduction paragraph.")])
...     .add_code_block("print('Hello, world!')", language="python")
...     .add_thematic_break()
...     .get_document())

Adding complex structures:

>>> builder = DocumentBuilder()
>>> builder.add_block_quote([Paragraph(content=[Text("Quote text")])])
>>> builder.add_list([ListItem(children=[Paragraph(content=[Text("Item 1")])])], ordered=False)
>>> builder.add_table(
...     rows=[TableRow(cells=[TableCell(content=[Text("Cell")])])],
...     header=TableRow(cells=[TableCell(content=[Text("Header")])])
... )
>>> doc = builder.get_document()

Adding multiple nodes at once:

>>> nodes = [
...     Heading(level=1, content=[Text("Title")]),
...     Paragraph(content=[Text("Paragraph 1")]),
...     Paragraph(content=[Text("Paragraph 2")])
... ]
>>> builder = DocumentBuilder()
>>> builder.add_nodes(nodes)
>>> doc = builder.get_document()

Initialize the document builder with an empty children list.

__init__() None

Initialize the document builder with an empty children list.

add_node(node: Node) DocumentBuilder

Add a node to the document.

Parameters:

node (Node) – Block-level node to add

Returns:

Self for method chaining

Return type:

DocumentBuilder

add_heading(level: int, content: list[Node]) DocumentBuilder

Add a heading to the document.

Parameters:
  • level (int) – Heading level (1-6)

  • content (list of Node) – Inline content

Returns:

Self for method chaining

Return type:

DocumentBuilder

add_paragraph(content: list[Node]) DocumentBuilder

Add a paragraph to the document.

Parameters:

content (list of Node) – Inline content

Returns:

Self for method chaining

Return type:

DocumentBuilder

add_code_block(content: str, language: str | None = None) DocumentBuilder

Add a code block to the document.

Parameters:
  • content (str) – Code content

  • language (str or None, default = None) – Programming language

Returns:

Self for method chaining

Return type:

DocumentBuilder

add_thematic_break() DocumentBuilder

Add a thematic break to the document.

Returns:

Self for method chaining

Return type:

DocumentBuilder

add_block_quote(children: list[Node]) DocumentBuilder

Add a block quote to the document.

Parameters:

children (list of Node) – Block-level content for the quote

Returns:

Self for method chaining

Return type:

DocumentBuilder

add_list(items: list[ListItem], ordered: bool = False, start: int = 1, tight: bool = True) DocumentBuilder

Add a list to the document.

Parameters:
  • items (list of ListItem) – List items

  • ordered (bool, default = False) – True for ordered list, False for unordered

  • start (int, default = 1) – Starting number for ordered lists

  • tight (bool, default = True) – Tight spacing (no blank lines between items)

Returns:

Self for method chaining

Return type:

DocumentBuilder

add_table(rows: list[TableRow], header: TableRow | None = None, alignments: list[Literal['left', 'center', 'right'] | None] | None = None, caption: str | None = None) DocumentBuilder

Add a table to the document.

Parameters:
  • rows (list of TableRow) – Table body rows

  • header (TableRow or None, default = None) – Optional header row

  • alignments (list of Alignment or None, optional) – Column alignments

  • caption (str or None, default = None) – Optional table caption

Returns:

Self for method chaining

Return type:

DocumentBuilder

add_html_block(content: str) DocumentBuilder

Add an HTML block to the document.

Parameters:

content (str) – Raw HTML content

Returns:

Self for method chaining

Return type:

DocumentBuilder

add_footnote_definition(identifier: str, content: list[Node]) DocumentBuilder

Add a footnote definition to the document.

Parameters:
  • identifier (str) – Footnote identifier/label

  • content (list of Node) – Block-level content for the footnote

Returns:

Self for method chaining

Return type:

DocumentBuilder

add_definition_list(items: list[tuple[DefinitionTerm, list[DefinitionDescription]]]) DocumentBuilder

Add a definition list to the document.

Parameters:

items (list of tuple) – List of (term, descriptions) tuples

Returns:

Self for method chaining

Return type:

DocumentBuilder

add_math_block(content: str, notation: Literal['latex', 'mathml', 'html'] = 'latex') DocumentBuilder

Add a math block to the document.

Parameters:
  • content (str) – Math expression content

  • notation ({"latex", "mathml", "html"}, default = "latex") – Math notation system

Returns:

Self for method chaining

Return type:

DocumentBuilder

add_nodes(nodes: list[Node]) DocumentBuilder

Add multiple nodes to the document at once.

Parameters:

nodes (list of Node) – Block-level nodes to add

Returns:

Self for method chaining

Return type:

DocumentBuilder

Examples

>>> builder = DocumentBuilder()
>>> builder.add_nodes([
...     Heading(level=1, content=[Text("Title")]),
...     Paragraph(content=[Text("Content")])
... ])
get_document() Document

Get the constructed document.

Returns:

Completed document

Return type:

Document