@@ -14,13 +14,15 @@ import (
14
14
15
15
// highlightSyntaxViaContent uses Chroma to lex code content and apply the appropriate tokenizer engine.
16
16
// If it can't find one, it defaults to JavaScript syntax highlighting.
17
- func highlightSyntaxViaContent (content string ) (htmlOut string ) {
17
+ func highlightSyntaxViaContent (content string , lang string ) (htmlOut string ) {
18
18
content = html .UnescapeString (content )
19
19
20
20
fallbackOut := html .EscapeString (content )
21
21
22
- // identify the language
23
- lexer := lexers .Analyse (content )
22
+ lexer := lexers .Get (lang )
23
+ if lexer == nil {
24
+ lexer = lexers .Analyse (content )
25
+ }
24
26
if lexer == nil {
25
27
lexer = lexers .Get (".js" )
26
28
}
@@ -71,19 +73,20 @@ func stripBlockTags(content string) (result string) {
71
73
return
72
74
}
73
75
74
- var codeBlockRegex = regexp .MustCompile (`(?s)<pre><code>(.*?)<\/code><\/pre>` )
76
+ var codeBlockRegex = regexp .MustCompile (`(?s)<pre(?:[^>]+?lang-(.+?)[\s"'])?.*? ><code>(.*?)<\/code><\/pre>` )
75
77
76
78
// HighlightCodeBlocks uses both highlightSyntaxViaContent stripCodeBlocks and returns the newly highlighted code HTML.
77
79
func HighlightCodeBlocks (html string ) string {
78
80
// Replace each code block with the highlighted version
79
81
highlightedHTML := codeBlockRegex .ReplaceAllStringFunc (html , func (codeBlock string ) string {
80
82
// Extract the code content from the code block
81
- codeContent := codeBlockRegex .FindStringSubmatch (codeBlock )[1 ]
83
+ matches := codeBlockRegex .FindStringSubmatch (codeBlock )
84
+ lang , codeContent := matches [1 ], matches [2 ]
82
85
83
86
codeContent = stripBlockTags (codeContent )
84
87
85
88
// Highlight the code content
86
- highlightedCode := highlightSyntaxViaContent (codeContent )
89
+ highlightedCode := highlightSyntaxViaContent (codeContent , lang )
87
90
88
91
// Replace the original code block with the highlighted version
89
92
highlightedCodeBlock := "<pre>" + highlightedCode + "</pre>"
0 commit comments