Fix heading anchors and add anchor links

Fixes #460
This commit is contained in:
rubenwardy
2025-06-19 18:37:03 +01:00
parent 2ddcbfb5ab
commit 21ef5f9b84
6 changed files with 25 additions and 3 deletions

View File

@@ -22,6 +22,7 @@ from markdown_it import MarkdownIt
from markdown_it.common.utils import unescapeAll, escapeHtml
from markdown_it.token import Token
from markdown_it.presets import gfm_like
from mdit_py_plugins.anchors import anchors_plugin
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.util import ClassNotFound
@@ -57,6 +58,7 @@ def render_code(self, tokens: Sequence[Token], idx, options, env):
gfm_like.make()
md = MarkdownIt("gfm-like", {"highlight": highlight_code})
md.use(anchors_plugin, permalink=True, permalinkSymbol="#", max_level=6)
md.add_render_rule("fence", render_code)
init_mention(md)
@@ -82,7 +84,8 @@ def get_headings(html: str):
root = []
stack = []
for heading in headings:
this = {"link": heading.get("id") or "", "text": heading.text, "children": []}
text = heading.find(text=True, recursive=False)
this = {"link": heading.get("id") or "", "text": text, "children": []}
this_level = int(heading.name[1:]) - 1
while this_level <= len(stack):

View File

@@ -57,12 +57,16 @@ def allow_class(_tag, name, value):
return name == "class" and value in ALLOWED_CSS
def allow_a(_tag, name, value):
return name in ["href", "title", "data-username"] or (name == "class" and value == "header-anchor")
ALLOWED_ATTRIBUTES = {
"h1": ["id"],
"h2": ["id"],
"h3": ["id"],
"h4": ["id"],
"a": ["href", "title", "data-username"],
"a": allow_a,
"img": ["src", "title", "alt"],
"code": allow_class,
"div": allow_class,