refactor: render highlight language (#38793)

Avoid CSS injection

More details are in the comment of CodeBlockAttributes
This commit is contained in:
wxiaoguang
2026-08-06 18:07:36 +08:00
committed by GitHub
parent 231ba1da19
commit 6ff3a65708
17 changed files with 112 additions and 56 deletions
+2 -2
View File
@@ -56,12 +56,12 @@ func Render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error
}
}()
preAttrs, codeAttrs := highlight.CodeBlockAttributes(lang)
lexer := highlight.DetectChromaLexerByFileName("", lang) // don't use content to detect, it is too slow
lexer = chroma.Coalesce(lexer)
sb := &strings.Builder{}
// include language-x class as part of commonmark spec
_ = ctx.RenderInternal.FormatWithSafeAttrs(sb, `<pre><code class="chroma language-%s">`, strings.ToLower(lexer.Config().Name))
_ = ctx.RenderInternal.FormatWithSafeAttrs(sb, `<pre %s><code %s>`, preAttrs, codeAttrs)
_, _ = sb.WriteString(string(highlight.RenderCodeByLexer(lexer, source)))
_, _ = sb.WriteString("</code></pre>")
return sb.String()