Skip to content

Commit

Permalink
Add code block highlight to orgmode back (#14222)
Browse files Browse the repository at this point in the history
Fix missed orgmode code block hightlight

Co-authored-by: zeripath <art27@cantab.net>
  • Loading branch information
lunny and zeripath authored Jun 23, 2021
1 parent 58501a2 commit f2babf3
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions modules/markup/orgmode/orgmode.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@ import (
"io"
"strings"

"code.gitea.io/gitea/modules/highlight"
"code.gitea.io/gitea/modules/markup"
"code.gitea.io/gitea/modules/util"

"github.com/alecthomas/chroma"
"github.com/alecthomas/chroma/lexers"
"github.com/niklasfasching/go-org/org"
)

Expand Down Expand Up @@ -41,6 +44,47 @@ func (Renderer) Extensions() []string {
// Render renders orgmode rawbytes to HTML
func Render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error {
htmlWriter := org.NewHTMLWriter()
htmlWriter.HighlightCodeBlock = func(source, lang string, inline bool) string {
var w strings.Builder
if _, err := w.WriteString(`<pre>`); err != nil {
return ""
}

lexer := lexers.Get(lang)
if lexer == nil && lang == "" {
lexer = lexers.Analyse(source)
if lexer == nil {
lexer = lexers.Fallback
}
lang = strings.ToLower(lexer.Config().Name)
}

if lexer == nil {
// include language-x class as part of commonmark spec
if _, err := w.WriteString(`<code class="chroma language-` + string(lang) + `">`); err != nil {
return ""
}
if _, err := w.WriteString(html.EscapeString(source)); err != nil {
return ""
}
} else {
// include language-x class as part of commonmark spec
if _, err := w.WriteString(`<code class="chroma language-` + string(lang) + `">`); err != nil {
return ""
}
lexer = chroma.Coalesce(lexer)

if _, err := w.WriteString(highlight.Code(lexer.Config().Filenames[0], source)); err != nil {
return ""
}
}

if _, err := w.WriteString("</code></pre>"); err != nil {
return ""
}

return w.String()
}

w := &Writer{
HTMLWriter: htmlWriter,
Expand Down

0 comments on commit f2babf3

Please sign in to comment.