Skip to content

Commit db95f1a

Browse files
lunnyzeripath
authored andcommitted
Add code block highlight to orgmode back (go-gitea#14222)
Fix missed orgmode code block hightlight Co-authored-by: zeripath <art27@cantab.net>
1 parent 94e6e37 commit db95f1a

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Diff for: modules/markup/orgmode/orgmode.go

+44
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,12 @@ import (
1111
"io"
1212
"strings"
1313

14+
"code.gitea.io/gitea/modules/highlight"
1415
"code.gitea.io/gitea/modules/markup"
1516
"code.gitea.io/gitea/modules/util"
1617

18+
"github.com/alecthomas/chroma"
19+
"github.com/alecthomas/chroma/lexers"
1720
"github.com/niklasfasching/go-org/org"
1821
)
1922

@@ -41,6 +44,47 @@ func (Renderer) Extensions() []string {
4144
// Render renders orgmode rawbytes to HTML
4245
func Render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error {
4346
htmlWriter := org.NewHTMLWriter()
47+
htmlWriter.HighlightCodeBlock = func(source, lang string, inline bool) string {
48+
var w strings.Builder
49+
if _, err := w.WriteString(`<pre>`); err != nil {
50+
return ""
51+
}
52+
53+
lexer := lexers.Get(lang)
54+
if lexer == nil && lang == "" {
55+
lexer = lexers.Analyse(source)
56+
if lexer == nil {
57+
lexer = lexers.Fallback
58+
}
59+
lang = strings.ToLower(lexer.Config().Name)
60+
}
61+
62+
if lexer == nil {
63+
// include language-x class as part of commonmark spec
64+
if _, err := w.WriteString(`<code class="chroma language-` + string(lang) + `">`); err != nil {
65+
return ""
66+
}
67+
if _, err := w.WriteString(html.EscapeString(source)); err != nil {
68+
return ""
69+
}
70+
} else {
71+
// include language-x class as part of commonmark spec
72+
if _, err := w.WriteString(`<code class="chroma language-` + string(lang) + `">`); err != nil {
73+
return ""
74+
}
75+
lexer = chroma.Coalesce(lexer)
76+
77+
if _, err := w.WriteString(highlight.Code(lexer.Config().Filenames[0], source)); err != nil {
78+
return ""
79+
}
80+
}
81+
82+
if _, err := w.WriteString("</code></pre>"); err != nil {
83+
return ""
84+
}
85+
86+
return w.String()
87+
}
4488

4589
w := &Writer{
4690
HTMLWriter: htmlWriter,

0 commit comments

Comments
 (0)