Skip to content

Commit 1e00b67

Browse files
committed
Get the innerText for markdown heading ids
1 parent 915dc08 commit 1e00b67

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

plain-pages/plain/pages/markdown.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from html.parser import HTMLParser
2+
13
import mistune
24
from pygments import highlight
35
from pygments.formatters import html
@@ -11,7 +13,8 @@ def heading(self, text, level, **attrs):
1113
"""Automatically add an ID to headings if one is not provided."""
1214

1315
if "id" not in attrs:
14-
attrs["id"] = slugify(text)
16+
inner_text = get_inner_text(text)
17+
attrs["id"] = slugify(inner_text)
1518

1619
return super().heading(text, level, **attrs)
1720

@@ -32,3 +35,19 @@ def render_markdown(content):
3235
renderer=renderer, plugins=["strikethrough", "table"]
3336
)
3437
return markdown(content)
38+
39+
40+
class InnerTextParser(HTMLParser):
41+
def __init__(self):
42+
super().__init__()
43+
self.text_content = []
44+
45+
def handle_data(self, data):
46+
# Collect all text data
47+
self.text_content.append(data.strip())
48+
49+
50+
def get_inner_text(html_content):
51+
parser = InnerTextParser()
52+
parser.feed(html_content)
53+
return " ".join([text for text in parser.text_content if text])

0 commit comments

Comments
 (0)