Merge pull request #5990 from Textualize/append-markdown-fix

fix for table of contents when using markdown.append
This commit is contained in:
Will McGugan
2025-07-25 20:50:24 +01:00
committed by GitHub
7 changed files with 243 additions and 35 deletions

View File

@@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).
## [5.0.1] - 2025-07-25
### Fixed
- Fixed appending to Markdown widgets that were constructed with an existing document https://github.com/Textualize/textual/pull/5990
## [5.0.0] - 2025-07-25
### Added
@@ -3015,6 +3021,7 @@ https://textual.textualize.io/blog/2022/11/08/version-040/#version-040
- New handler system for messages that doesn't require inheritance
- Improved traceback handling
[5.0.1]: https://github.com/Textualize/textual/compare/v5.0.0...v5.0.1
[5.0.0]: https://github.com/Textualize/textual/compare/v4.1.0...v5.0.0
[4.0.0]: https://github.com/Textualize/textual/compare/v3.7.1...v4.0.0
[3.7.1]: https://github.com/Textualize/textual/compare/v3.7.0...v3.7.1

View File

@@ -1,6 +1,6 @@
[tool.poetry]
name = "textual"
version = "5.0.0"
version = "5.0.1"
homepage = "https://github.com/Textualize/textual"
repository = "https://github.com/Textualize/textual"
documentation = "https://textual.textualize.io/"

View File

@@ -271,7 +271,7 @@ class Footer(ScrollableContainer, can_focus=False, can_focus_children=False):
def bindings_changed(screen: Screen) -> None:
"""Update bindings after a short delay to avoid flicker."""
self.set_timer(1 / 20, lambda: self.bindings_changed(screen))
self.call_after_refresh(self.bindings_changed, screen)
self.screen.bindings_updated_signal.subscribe(self, bindings_changed)

View File

@@ -354,6 +354,8 @@ class MarkdownBlock(Static):
class MarkdownHeader(MarkdownBlock):
"""Base class for a Markdown header."""
LEVEL = 0
DEFAULT_CSS = """
MarkdownHeader {
color: $text;
@@ -366,6 +368,8 @@ class MarkdownHeader(MarkdownBlock):
class MarkdownH1(MarkdownHeader):
"""An H1 Markdown header."""
LEVEL = 1
DEFAULT_CSS = """
MarkdownH1 {
content-align: center middle;
@@ -379,6 +383,8 @@ class MarkdownH1(MarkdownHeader):
class MarkdownH2(MarkdownHeader):
"""An H2 Markdown header."""
LEVEL = 2
DEFAULT_CSS = """
MarkdownH2 {
color: $markdown-h2-color;
@@ -391,6 +397,8 @@ class MarkdownH2(MarkdownHeader):
class MarkdownH3(MarkdownHeader):
"""An H3 Markdown header."""
LEVEL = 3
DEFAULT_CSS = """
MarkdownH3 {
color: $markdown-h3-color;
@@ -405,6 +413,8 @@ class MarkdownH3(MarkdownHeader):
class MarkdownH4(MarkdownHeader):
"""An H4 Markdown header."""
LEVEL = 4
DEFAULT_CSS = """
MarkdownH4 {
color: $markdown-h4-color;
@@ -418,6 +428,8 @@ class MarkdownH4(MarkdownHeader):
class MarkdownH5(MarkdownHeader):
"""An H5 Markdown header."""
LEVEL = 5
DEFAULT_CSS = """
MarkdownH5 {
color: $markdown-h5-color;
@@ -431,6 +443,8 @@ class MarkdownH5(MarkdownHeader):
class MarkdownH6(MarkdownHeader):
"""An H6 Markdown header."""
LEVEL = 6
DEFAULT_CSS = """
MarkdownH6 {
color: $markdown-h6-color;
@@ -574,7 +588,7 @@ class MarkdownOrderedList(MarkdownList):
bullet.symbol = f"{number}{suffix}".rjust(symbol_size + 1)
yield Horizontal(bullet, Vertical(*block._blocks))
# self._blocks.clear()
self._blocks.clear()
class MarkdownTableCellContents(Static):
@@ -974,11 +988,21 @@ class Markdown(Widget):
self._initial_markdown: str | None = markdown
self._markdown = ""
self._parser_factory = parser_factory
self._table_of_contents: TableOfContentsType = []
self._table_of_contents: TableOfContentsType | None = None
self._open_links = open_links
self._last_parsed_line = 0
self._theme = ""
@property
def table_of_contents(self) -> TableOfContentsType:
"""The document's table of contents."""
if self._table_of_contents is None:
self._table_of_contents = [
(header.LEVEL, header._content.plain, header.id)
for header in self.query_children(MarkdownHeader)
]
return self._table_of_contents
class TableOfContentsUpdated(Message):
"""The table of contents was updated."""
@@ -1182,16 +1206,11 @@ class Markdown(Widget):
"""
return None
def _parse_markdown(
self,
tokens: Iterable[Token],
table_of_contents: TableOfContentsType,
) -> Iterable[MarkdownBlock]:
def _parse_markdown(self, tokens: Iterable[Token]) -> Iterable[MarkdownBlock]:
"""Create a stream of MarkdownBlock widgets from markdown.
Args:
tokens: List of tokens.
table_of_contents: List to store table of contents.
Yields:
Widgets for mounting.
@@ -1251,10 +1270,7 @@ class Markdown(Widget):
elif token_type.endswith("_close"):
block = stack.pop()
if token.type == "heading_close":
heading = block._content.plain
level = int(token.tag[1:])
block.id = f"{slug(heading)}-{len(table_of_contents) + 1}"
table_of_contents.append((level, heading, block.id))
block.id = f"heading-{slug(block._content.plain)}-{id(block)}"
if stack:
stack[-1]._blocks.append(block)
else:
@@ -1262,7 +1278,9 @@ class Markdown(Widget):
elif token_type == "inline":
stack[-1].build_from_token(token)
elif token_type in ("fence", "code_block"):
fence = get_block_class(token_type)(self, token, token.content.rstrip())
fence_class = get_block_class(token_type)
assert issubclass(fence_class, MarkdownFence)
fence = fence_class(self, token, token.content.rstrip())
if stack:
stack[-1]._blocks.append(fence)
else:
@@ -1276,13 +1294,21 @@ class Markdown(Widget):
yield external
def _build_from_source(self, markdown: str) -> list[MarkdownBlock]:
"""Build blocks from markdown source.
Args:
markdown: A Markdown document, or partial document.
Returns:
A list of MarkdownBlock instances.
"""
parser = (
MarkdownIt("gfm-like")
if self._parser_factory is None
else self._parser_factory()
)
tokens = parser.parse(markdown)
return list(self._parse_markdown(tokens, []))
return list(self._parse_markdown(tokens))
def update(self, markdown: str) -> AwaitComplete:
"""Update the document with new Markdown.
@@ -1300,9 +1326,9 @@ class Markdown(Widget):
else self._parser_factory()
)
table_of_contents: TableOfContentsType = []
markdown_block = self.query("MarkdownBlock")
self._markdown = markdown
self._table_of_contents = None
async def await_update() -> None:
"""Update in batches."""
@@ -1333,7 +1359,7 @@ class Markdown(Widget):
await self.mount_all(batch)
removed = True
for block in self._parse_markdown(tokens, table_of_contents):
for block in self._parse_markdown(tokens):
batch.append(block)
if len(batch) == BATCH_SIZE:
await mount_batch(batch)
@@ -1343,13 +1369,13 @@ class Markdown(Widget):
if not removed:
await markdown_block.remove()
if table_of_contents != self._table_of_contents:
self._table_of_contents = table_of_contents
self.post_message(
Markdown.TableOfContentsUpdated(
self, self._table_of_contents
).set_sender(self)
)
lines = markdown.splitlines()
self._last_parsed_line = len(lines) - (1 if lines and lines[-1] else 0)
self.post_message(
Markdown.TableOfContentsUpdated(
self, self.table_of_contents
).set_sender(self)
)
return AwaitComplete(await_update())
@@ -1368,7 +1394,6 @@ class Markdown(Widget):
else self._parser_factory()
)
table_of_contents: TableOfContentsType = []
self._markdown = self.source + markdown
updated_source = "".join(
self._markdown.splitlines(keepends=True)[self._last_parsed_line :]
@@ -1387,7 +1412,7 @@ class Markdown(Widget):
self._last_parsed_line += token.map[0]
break
new_blocks = list(self._parse_markdown(tokens, table_of_contents))
new_blocks = list(self._parse_markdown(tokens))
for block in new_blocks:
start, end = block.source_range
block.source_range = (
@@ -1409,12 +1434,13 @@ class Markdown(Widget):
if new_blocks:
await self.mount_all(new_blocks)
self._table_of_contents = table_of_contents
self.post_message(
Markdown.TableOfContentsUpdated(
self, self._table_of_contents
).set_sender(self)
)
if any(isinstance(block, MarkdownHeader) for block in new_blocks):
self._table_of_contents = None
self.post_message(
Markdown.TableOfContentsUpdated(
self, self.table_of_contents
).set_sender(self)
)
return AwaitComplete(await_append())

View File

@@ -52,6 +52,7 @@ async def test_footer_bindings() -> None:
async with app.run_test() as pilot:
await pilot.pause()
assert app_binding_count == 0
await app.wait_for_refresh()
await pilot.click("Footer", offset=(1, 0))
assert app_binding_count == 1
await pilot.click("Footer")

View File

@@ -0,0 +1,153 @@
<svg class="rich-terminal" viewBox="0 0 994 635.5999999999999" xmlns="http://www.w3.org/2000/svg">
<!-- Generated with Rich https://www.textualize.io -->
<style>
@font-face {
font-family: "Fira Code";
src: local("FiraCode-Regular"),
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2") format("woff2"),
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff") format("woff");
font-style: normal;
font-weight: 400;
}
@font-face {
font-family: "Fira Code";
src: local("FiraCode-Bold"),
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Bold.woff2") format("woff2"),
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Bold.woff") format("woff");
font-style: bold;
font-weight: 700;
}
.terminal-matrix {
font-family: Fira Code, monospace;
font-size: 20px;
line-height: 24.4px;
font-variant-east-asian: full-width;
}
.terminal-title {
font-size: 18px;
font-weight: bold;
font-family: arial;
}
.terminal-r1 { fill: #c5c8c6 }
.terminal-r2 { fill: #0178d4;font-weight: bold }
.terminal-r3 { fill: #e0e0e0;font-weight: bold }
.terminal-r4 { fill: #e0e0e0 }
.terminal-r5 { fill: #e0e0e0;font-style: italic; }
</style>
<defs>
<clipPath id="terminal-clip-terminal">
<rect x="0" y="0" width="975.0" height="584.5999999999999" />
</clipPath>
<clipPath id="terminal-line-0">
<rect x="0" y="1.5" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-1">
<rect x="0" y="25.9" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-2">
<rect x="0" y="50.3" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-3">
<rect x="0" y="74.7" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-4">
<rect x="0" y="99.1" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-5">
<rect x="0" y="123.5" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-6">
<rect x="0" y="147.9" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-7">
<rect x="0" y="172.3" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-8">
<rect x="0" y="196.7" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-9">
<rect x="0" y="221.1" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-10">
<rect x="0" y="245.5" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-11">
<rect x="0" y="269.9" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-12">
<rect x="0" y="294.3" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-13">
<rect x="0" y="318.7" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-14">
<rect x="0" y="343.1" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-15">
<rect x="0" y="367.5" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-16">
<rect x="0" y="391.9" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-17">
<rect x="0" y="416.3" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-18">
<rect x="0" y="440.7" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-19">
<rect x="0" y="465.1" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-20">
<rect x="0" y="489.5" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-21">
<rect x="0" y="513.9" width="976" height="24.65"/>
</clipPath>
<clipPath id="terminal-line-22">
<rect x="0" y="538.3" width="976" height="24.65"/>
</clipPath>
</defs>
<rect fill="#292929" stroke="rgba(255,255,255,0.35)" stroke-width="1" x="1" y="1" width="992" height="633.6" rx="8"/><text class="terminal-title" fill="#c5c8c6" text-anchor="middle" x="496" y="27">MyApp</text>
<g transform="translate(26,22)">
<circle cx="0" cy="0" r="7" fill="#ff5f57"/>
<circle cx="22" cy="0" r="7" fill="#febc2e"/>
<circle cx="44" cy="0" r="7" fill="#28c840"/>
</g>
<g transform="translate(9, 41)" clip-path="url(#terminal-clip-terminal)">
<rect fill="#121212" x="0" y="1.5" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="25.9" width="24.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="24.4" y="25.9" width="73.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="97.6" y="25.9" width="878.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="50.3" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="74.7" width="24.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="24.4" y="74.7" width="61" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="85.4" y="74.7" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="97.6" y="74.7" width="61" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="158.6" y="74.7" width="817.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="99.1" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="123.5" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="147.9" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="172.3" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="196.7" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="221.1" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="245.5" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="269.9" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="294.3" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="318.7" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="343.1" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="367.5" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="391.9" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="416.3" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="440.7" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="465.1" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="489.5" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="513.9" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="538.3" width="976" height="24.65" shape-rendering="crispEdges"/><rect fill="#121212" x="0" y="562.7" width="976" height="24.65" shape-rendering="crispEdges"/>
<g class="terminal-matrix">
<text class="terminal-r1" x="976" y="20" textLength="12.2" clip-path="url(#terminal-line-0)">
</text><text class="terminal-r2" x="24.4" y="44.4" textLength="73.2" clip-path="url(#terminal-line-1)">Header</text><text class="terminal-r1" x="976" y="44.4" textLength="12.2" clip-path="url(#terminal-line-1)">
</text><text class="terminal-r1" x="976" y="68.8" textLength="12.2" clip-path="url(#terminal-line-2)">
</text><text class="terminal-r3" x="24.4" y="93.2" textLength="61" clip-path="url(#terminal-line-3)">Hello</text><text class="terminal-r5" x="97.6" y="93.2" textLength="61" clip-path="url(#terminal-line-3)">World</text><text class="terminal-r1" x="976" y="93.2" textLength="12.2" clip-path="url(#terminal-line-3)">
</text><text class="terminal-r1" x="976" y="117.6" textLength="12.2" clip-path="url(#terminal-line-4)">
</text><text class="terminal-r1" x="976" y="142" textLength="12.2" clip-path="url(#terminal-line-5)">
</text><text class="terminal-r1" x="976" y="166.4" textLength="12.2" clip-path="url(#terminal-line-6)">
</text><text class="terminal-r1" x="976" y="190.8" textLength="12.2" clip-path="url(#terminal-line-7)">
</text><text class="terminal-r1" x="976" y="215.2" textLength="12.2" clip-path="url(#terminal-line-8)">
</text><text class="terminal-r1" x="976" y="239.6" textLength="12.2" clip-path="url(#terminal-line-9)">
</text><text class="terminal-r1" x="976" y="264" textLength="12.2" clip-path="url(#terminal-line-10)">
</text><text class="terminal-r1" x="976" y="288.4" textLength="12.2" clip-path="url(#terminal-line-11)">
</text><text class="terminal-r1" x="976" y="312.8" textLength="12.2" clip-path="url(#terminal-line-12)">
</text><text class="terminal-r1" x="976" y="337.2" textLength="12.2" clip-path="url(#terminal-line-13)">
</text><text class="terminal-r1" x="976" y="361.6" textLength="12.2" clip-path="url(#terminal-line-14)">
</text><text class="terminal-r1" x="976" y="386" textLength="12.2" clip-path="url(#terminal-line-15)">
</text><text class="terminal-r1" x="976" y="410.4" textLength="12.2" clip-path="url(#terminal-line-16)">
</text><text class="terminal-r1" x="976" y="434.8" textLength="12.2" clip-path="url(#terminal-line-17)">
</text><text class="terminal-r1" x="976" y="459.2" textLength="12.2" clip-path="url(#terminal-line-18)">
</text><text class="terminal-r1" x="976" y="483.6" textLength="12.2" clip-path="url(#terminal-line-19)">
</text><text class="terminal-r1" x="976" y="508" textLength="12.2" clip-path="url(#terminal-line-20)">
</text><text class="terminal-r1" x="976" y="532.4" textLength="12.2" clip-path="url(#terminal-line-21)">
</text><text class="terminal-r1" x="976" y="556.8" textLength="12.2" clip-path="url(#terminal-line-22)">
</text>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 10 KiB

View File

@@ -4423,19 +4423,40 @@ def test_markdown_append(snap_compare):
assert snap_compare(MDApp(), press=["1", "wait:500"])
def test_append_with_initial_document(snap_compare):
"""Test appending to an an existing document works.
You should a header, followed by Hello World on the next line.
"Hello" will be in bold, and "World" in italics.
"""
TEXT = """\
### Header
**Hello**"""
class MyApp(App):
def compose(self):
yield Markdown(TEXT)
async def on_mount(self) -> None:
await self.query_one(Markdown).append(" *World*")
assert snap_compare(MyApp())
def test_text_area_css_theme_updates_background(snap_compare):
"""Regression test for https://github.com/Textualize/textual/issues/5964"""
class TextAreaThemeApp(App):
def compose(self) -> ComposeResult:
text_area_control = TextArea(
text_area_control = TextArea(
"This TextArea theme is always `css`.",
theme="css",
id="text-area-control",
)
text_area_control.cursor_blink = False
text_area_variable = TextArea(
text_area_variable = TextArea(
"This TextArea theme changes from `github_light` to `css`.\n"
"The colors should match the TextArea above.",
theme="github_light",