From f2babf334676f9c16a540153432bc6e4ebf62423 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 24 Jun 2021 04:45:47 +0800 Subject: [PATCH] Add code block highlight to orgmode back (#14222) Fix missed orgmode code block hightlight Co-authored-by: zeripath --- modules/markup/orgmode/orgmode.go | 44 +++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/modules/markup/orgmode/orgmode.go b/modules/markup/orgmode/orgmode.go index 96e67f90c..851fc97f9 100644 --- a/modules/markup/orgmode/orgmode.go +++ b/modules/markup/orgmode/orgmode.go @@ -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" ) @@ -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(`
`); 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(``); 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(``); 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("
"); err != nil { + return "" + } + + return w.String() + } w := &Writer{ HTMLWriter: htmlWriter,