Skip to content

Markdown table of contents can get out of sync after quick updatesΒ #6112

@TomJGooding

Description

@TomJGooding

Consider this simple attempt at a markdown editor app:

from textual import on
from textual.app import App, ComposeResult
from textual.containers import Horizontal
from textual.widgets import Footer, MarkdownViewer, TextArea

MARKDOWN = """\
# Heading 1

After quickly typing some text below,
try selecting from the Table of Contents.

## Heading 2

Really *mash* those keys! \
"""


class MarkdownEditorApp(App):
    def compose(self) -> ComposeResult:
        with Horizontal():
            yield TextArea.code_editor(language="markdown")
            yield MarkdownViewer()

        yield Footer()

    def on_mount(self) -> None:
        text_area = self.query_one(TextArea)
        text_area.load_text(MARKDOWN)
        text_area.move_cursor(text_area.document.end)

    @on(TextArea.Changed)
    def update_markdown_preview(self, event: TextArea.Changed) -> None:
        new_markdown = event.text_area.text
        self.query_one(MarkdownViewer).document.update(new_markdown)


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

If you quickly type some text (really mash those keys!) to update the markdown, when you try to select from the table of contents the app will crash with a NoMatches error.

The problem is that the Markdown table of contents can quickly get out of sync with the actual heading widget ID's, which depend on their unique Python object id().

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions