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()
+2 -2
View File
@@ -83,12 +83,12 @@ func TestRender_Source(t *testing.T) {
int a;
#+end_src
`, `<div class="src src-c">
<pre><code class="chroma language-c"><span class="kt">int</span> <span class="n">a</span><span class="p">;</span></code></pre>
<pre class="code-block"><code class="chroma language-c" data-code-language="c"><span class="kt">int</span> <span class="n">a</span><span class="p">;</span></code></pre>
</div>`)
}
func TestRender_IncludeLink(t *testing.T) {
testRender(t, `#+INCLUDE: "./other.org" src text`, `<div class="src src-text">
<pre><code class="chroma language-plaintext">#+INCLUDE: [[other.org]]</code></pre>
<pre class="code-block"><code class="chroma language-text" data-code-language="text">#+INCLUDE: [[other.org]]</code></pre>
</div>`)
}