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
+3 -11
View File
@@ -11,6 +11,7 @@ import (
"io"
"strings"
"gitea.dev/modules/highlight"
"gitea.dev/modules/htmlutil"
"gitea.dev/modules/log"
"gitea.dev/modules/markup"
@@ -78,17 +79,8 @@ func (r *GoldmarkRender) Convert(source []byte, writer io.Writer, opts ...parser
func (r *GoldmarkRender) highlightingRenderer(w util.BufWriter, c highlighting.CodeBlockContext, entering bool) {
if entering {
languageBytes, _ := c.Language()
languageStr := giteautil.IfZero(string(languageBytes), "text")
preClasses := "code-block"
if languageStr == "mermaid" || languageStr == "math" {
preClasses += " is-loading"
}
// include language-x class as part of commonmark spec, "chroma" class is used to highlight the code
// the "display" class is used by "js/markup/math.ts" to render the code element as a block
// the "math.ts" strictly depends on the structure: <pre class="code-block is-loading"><code class="language-math display">...</code></pre>
err := r.ctx.RenderInternal.FormatWithSafeAttrs(w, `<div class="code-block-container code-overflow-scroll"><pre class="%s"><code class="chroma language-%s display">`, preClasses, languageStr)
preAttrs, codeAttrs := highlight.CodeBlockAttributes(string(languageBytes))
err := r.ctx.RenderInternal.FormatWithSafeAttrs(w, `<div class="code-block-container code-overflow-scroll"><pre %s><code %s>`, preAttrs, codeAttrs)
if err != nil {
return
}