Skip to content

MarkdownDocument

Markdown document builder class.

The purpose of this class is to generate markdown programatically with an object oriented interface.

The document is created by initalising this class:

doc = MarkdownDocument()

From here the object has methods to manipulate the document.

add(self, text)

Unmodified raw string injection into the document.

Parameters:

Name Type Description Default
text str

Text to inject.

required

codeblock(self, language='')

Codeblock context manager.

Wraps paragraphs in codeblock backticks with optional syntax highlighting.

with doc.codeblock(language="python"):
    doc.paragraph(
    """
    for i in range(100):
        print(i)
    """
    )

Parameters:

Name Type Description Default
language str

Syntax highlighting language.

''

collapsed(self, summary)

Adds collapsable section to the document.

Uses html tags to add a details block, with summary.

Parameters:

Name Type Description Default
summary str

Summary for the collapsed block..

required

heading(self, heading=None, silent=False, level=None)

Adds a Markdown Heading to the document.

There's two entrypoints using this method:

  • As a context manager: This is used if you want to use nested headings, in a heading level aware context.

    Repeatedly nesting more headings increases the heading level.

    with doc.heading("Title"):
        text.paragraph("Blurb under the title heading")
    
  • As a document element: This is used to inject a heading as is, at the current document header level, or if the level argument is used, at a specific level.

    doc.header("Sub Sub Heading", level=3)
    

Parameters:

Name Type Description Default
heading Optional[str]

Text to be used as a heading. Defaults to None.

None
silent bool

Skip printing the heading. Defaults to False.

False
level Optional[int]

Static level to assign to the heading. Defaults to None.

None

Returns:

Type Description
_MarkdownHeading

Heading object.

horizontal_line(self)

Add horizontal line to document.

indentblock(self)

Returns indented context manager.

All elements defined in this with section will be indented.

with doc.indentblock():
    doc.text("This text will be indented by 4 spaces")

injector(self, anchor)

Add inline comment to use as an injector anchor.

Using and abusing html comments, as they are not rendered in markdown.

Renders <!--- markdown-toolkit:anchor ---> tags into the document.

Parameters:

Name Type Description Default
anchor str

Unique identifier string for the anchor.

required

linebreak(self)

Adds a linebreak to the document.

list(self, item, ordered=False, prefix=None)

Adds a Markdown List to the document.

This method produces ordered and unordered lists.

There's two entrypoints using this method:

  • As a context manager: This method creates a nested list context.

    The context manager creates a new list item, but inside the with block any new created lists will be children of this list.

    with doc.list("Parent Item"):
        doc.list("Child Item")
    
  • As a document element: This method creates a list item as is, at the current document indentation level.

    doc.list("List item", ordered=True)
    

Parameters:

Name Type Description Default
item str

List item string to be used.

required
ordered bool

If the list is ordered or not. Defaults to False.

False
prefix Optional[str]

Custom prefix on list items. Defaults to None.

None

Returns:

Type Description
_MarkdownList

description

paragraph(self, text, linebreak=True)

Adds a paragraph to the document.

This differs from adding text to the document in the text method in a few ways:

  • By default it adds a linebreak after the text to force a paragraph break in the document.
  • It uses the cleandoc function to clean multitline indentation whitespace up.

Parameters:

Name Type Description Default
text str

Text to add to the document.

required
linebreak Union[int, bool]

Enables the trailing linebreak. Defaults to True.

True

render(self, trailing_whitespace=False)

Renders document to multiline string.

Parameters:

Name Type Description Default
trailing_whitespace bool

Add linebreak to the end of the document. Defaults to False.

False

Returns:

Type Description
str

Rendered document.

table(self, raw_table=None, *, titles=None, sort_by=None)

Adds a Markdown Table to the document.

This method produces github flavoured markdown tables.

There's two entrypoints using this method:

  • As a context manager: This is if you do not want to wrangle a large dataset in one go, so you can lazy add to the table row at a time.

    You have to define the table title headings at initialisation time.

    with doc.table(titles=["example","headings]) as table:
        table.add_row(example="abc", headings="123")
    
  • As a document element: This is if you have a list of dictionaries and you just want to render them using the dictionary key value pairs.

    doc.table(
        [
            {"key": 123, "value": "example"},
            {"key": 456, "value": "another field"}
        ]
    )
    

Parameters:

Name Type Description Default
raw_table Optional[list[dict]]

Raw table to render. Defaults to None.

None
titles Optional[list]

Table titles. Defaults to None.

None
sort_by Optional[str]

Table title to sort by. Defaults to None.

None

Returns:

Type Description
_MarkdownTable

Object with helper methods.

text(self, text='')

Add text to document, taking into account indent level.

Parameters:

Name Type Description Default
text str

Text to add to the document. Defaults to "".

''

write(self, file)

Helper method to write the document contents to a file or filelike object.

Parameters:

Name Type Description Default
file Union[str, StringIO]

Path to file, or filelike object already opened.

required
Back to top