Skip to content

Markdown

Added in version 0.11.0

A widget to display a Markdown document.

  • Focusable
  • Container

Tip

See MarkdownViewer for a widget that adds additional features such as a Table of Contents.

Example

The following example displays Markdown from a string.

MarkdownExampleApp Markdown • Typography emphasisstronginline code etc. • Headers • Lists • Syntax highlighted code blocks • Tables and more ▂▂ Quotes I must not fear. Fear is the mind-killer. Fear is the little-death that brings total obliteration. I will face my fear. I will permit it to pass over me and through me. And when it has gone past, I will turn the inner eye to see its path. Where the fear has gone there will be nothing. Only I will remain.

from textual.app import App, ComposeResult
from textual.widgets import Markdown

EXAMPLE_MARKDOWN = """\
## Markdown

- Typography *emphasis*, **strong**, `inline code` etc.    
- Headers    
- Lists    
- Syntax highlighted code blocks
- Tables and more

## Quotes

> I must not fear.
> > Fear is the mind-killer.
> > Fear is the little-death that brings total obliteration.
> > I will face my fear.
> > > I will permit it to pass over me and through me.
> > > And when it has gone past, I will turn the inner eye to see its path.
> > > Where the fear has gone there will be nothing. Only I will remain.

## Tables

| Name            | Type   | Default | Description                        |
| --------------- | ------ | ------- | ---------------------------------- |
| `show_header`   | `bool` | `True`  | Show the table header              |
| `fixed_rows`    | `int`  | `0`     | Number of fixed rows               |
| `fixed_columns` | `int`  | `0`     | Number of fixed columns            |

## Code blocks

```python
def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
    \"\"\"Iterate and generate a tuple with a flag for last value.\"\"\"
    iter_values = iter(values)
    try:
        previous_value = next(iter_values)
    except StopIteration:
        return
    for value in iter_values:
        yield False, previous_value
        previous_value = value
    yield True, previous_value
```


"""


class MarkdownExampleApp(App):

    def compose(self) -> ComposeResult:
        markdown = Markdown(EXAMPLE_MARKDOWN)
        markdown.code_indent_guides = False
        yield markdown


if __name__ == "__main__":
    app = MarkdownExampleApp()
    app.run()

Reactive Attributes

This widget has no reactive attributes.

Messages

Bindings

This widget has no bindings.

Component Classes

The markdown widget provides the following component classes:

See Also


Bases: Widget

Parameters:

Name Type Description Default

markdown

str | None

String containing Markdown or None to leave blank for now.

None

name

str | None

The name of the widget.

None

id

str | None

The ID of the widget in the DOM.

None

classes

str | None

The CSS classes of the widget.

None

parser_factory

Callable[[], MarkdownIt] | None

A factory function to return a configured MarkdownIt instance. If None, a "gfm-like" parser is used.

None

open_links

bool

Open links automatically. If you set this to False, you can handle the LinkClicked events.

True

BLOCKS class-attribute instance-attribute

BLOCKS = {
    "h1": MarkdownH1,
    "h2": MarkdownH2,
    "h3": MarkdownH3,
    "h4": MarkdownH4,
    "h5": MarkdownH5,
    "h6": MarkdownH6,
    "hr": MarkdownHorizontalRule,
    "paragraph_open": MarkdownParagraph,
    "blockquote_open": MarkdownBlockQuote,
    "bullet_list_open": MarkdownBulletList,
    "ordered_list_open": MarkdownOrderedList,
    "list_item_ordered_open": MarkdownOrderedListItem,
    "list_item_unordered_open": MarkdownUnorderedListItem,
    "table_open": MarkdownTable,
    "tbody_open": MarkdownTBody,
    "thead_open": MarkdownTHead,
    "tr_open": MarkdownTR,
    "th_open": MarkdownTH,
    "td_open": MarkdownTD,
    "fence": MarkdownFence,
    "code_block": MarkdownFence,
}

Mapping of block names on to a widget class.

BULLETS class-attribute instance-attribute

BULLETS = ['• ', '▪ ', '‣ ', '⭑ ', '◦ ']

Unicode bullets used for unordered lists.

source property

source

The markdown source.

table_of_contents property

table_of_contents

The document's table of contents.

LinkClicked

LinkClicked(markdown, href)

Bases: Message

A link in the document was clicked.

control property

control

The Markdown widget containing the link clicked.

This is an alias for LinkClicked.markdown and is used by the on decorator.

href instance-attribute

href = unquote(href)

The link that was selected.

markdown instance-attribute

markdown = markdown

The Markdown widget containing the link clicked.

TableOfContentsSelected

TableOfContentsSelected(markdown, block_id)

Bases: Message

An item in the TOC was selected.

block_id instance-attribute

block_id = block_id

ID of the block that was selected.

control property

control

The Markdown widget where the selected item is.

This is an alias for TableOfContentsSelected.markdown and is used by the on decorator.

markdown instance-attribute

markdown = markdown

The Markdown widget where the selected item is.

TableOfContentsUpdated

TableOfContentsUpdated(markdown, table_of_contents)

Bases: Message

The table of contents was updated.

control property

control

The Markdown widget associated with the table of contents.

This is an alias for TableOfContentsUpdated.markdown and is used by the on decorator.

markdown instance-attribute

markdown = markdown

The Markdown widget associated with the table of contents.

table_of_contents instance-attribute

table_of_contents = table_of_contents

Table of contents.

append

append(markdown)

Append to markdown.

Parameters:

Name Type Description Default

markdown

str

A fragment of markdown to be appended.

required

Returns:

Type Description
AwaitComplete

An optionally awaitable object. Await this to ensure that the markdown has been append by the next line.

get_block_class

get_block_class(block_name)

Get the block widget class.

Parameters:

Name Type Description Default

block_name

str

Name of the block.

required

Returns:

Type Description
type[MarkdownBlock]

A MarkdownBlock class

get_stream classmethod

get_stream(markdown)

Get a MarkdownStream instance to stream Markdown in the background.

If you append to the Markdown document many times a second, it is possible the widget won't be able to update as fast as you write (occurs around 20 appends per second). It will still work, but the user will have to wait for the UI to catch up after the document has be retrieved.

Using a MarkdownStream will combine several updates in to one as necessary to keep up with the incoming data.

example:

# self.get_chunk is a hypothetical method that retrieves a
# markdown fragment from the network
@work
async def stream_markdown(self) -> None:
    markdown_widget = self.query_one(Markdown)
    container = self.query_one(VerticalScroll)
    container.anchor()

    stream = Markdown.get_stream(markdown_widget)
    try:
        while (chunk:= await self.get_chunk()) is not None:
            await stream.write(chunk)
    finally:
        await stream.stop()

Parameters:

Name Type Description Default

markdown

Markdown

A Markdown widget instance.

required

Returns:

Type Description
MarkdownStream

The Markdown stream object.

goto_anchor

goto_anchor(anchor)

Try and find the given anchor in the current document.

Parameters:

Name Type Description Default

anchor

str

The anchor to try and find.

required
Note

The anchor is found by looking at all of the headings in the document and finding the first one whose slug matches the anchor.

Note that the slugging method used is similar to that found on GitHub.

Returns:

Type Description
bool

True when the anchor was found in the current document, False otherwise.

load async

load(path)

Load a new Markdown document.

Parameters:

Name Type Description Default

path

Path

Path to the document.

required

Raises:

Type Description
OSError

If there was some form of error loading the document.

Note

The exceptions that can be raised by this method are all of those that can be raised by calling Path.read_text.

sanitize_location staticmethod

sanitize_location(location)

Given a location, break out the path and any anchor.

Parameters:

Name Type Description Default

location

str

The location to sanitize.

required

Returns:

Type Description
Path

A tuple of the path to the location cleaned of any anchor, plus

str

the anchor (or an empty string if none was found).

unhandled_token

unhandled_token(token)

Process an unhandled token.

Parameters:

Name Type Description Default

token

Token

The MarkdownIt token to handle.

required

Returns:

Type Description
MarkdownBlock | None

Either a widget to be added to the output, or None.

update

update(markdown)

Update the document with new Markdown.

Parameters:

Name Type Description Default

markdown

str

A string containing Markdown.

required

Returns:

Type Description
AwaitComplete

An optionally awaitable object. Await this to ensure that all children have been mounted.