Skip to content

Commit 23b8ed8

Browse files
authored
improvement: use lang-* classes declared in snippet markup (#97)
* improvement: use lang-* classes declared in snippet markup * fix: don't require snippet lang classes in code blocks * fix: constrain greedy code block match
1 parent bf53007 commit 23b8ed8

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

src/utils/syntax.go

+9-6
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,15 @@ import (
1414

1515
// highlightSyntaxViaContent uses Chroma to lex code content and apply the appropriate tokenizer engine.
1616
// 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) {
1818
content = html.UnescapeString(content)
1919

2020
fallbackOut := html.EscapeString(content)
2121

22-
// identify the language
23-
lexer := lexers.Analyse(content)
22+
lexer := lexers.Get(lang)
23+
if lexer == nil {
24+
lexer = lexers.Analyse(content)
25+
}
2426
if lexer == nil {
2527
lexer = lexers.Get(".js")
2628
}
@@ -71,19 +73,20 @@ func stripBlockTags(content string) (result string) {
7173
return
7274
}
7375

74-
var codeBlockRegex = regexp.MustCompile(`(?s)<pre><code>(.*?)<\/code><\/pre>`)
76+
var codeBlockRegex = regexp.MustCompile(`(?s)<pre(?:[^>]+?lang-(.+?)[\s"'])?.*?><code>(.*?)<\/code><\/pre>`)
7577

7678
// HighlightCodeBlocks uses both highlightSyntaxViaContent stripCodeBlocks and returns the newly highlighted code HTML.
7779
func HighlightCodeBlocks(html string) string {
7880
// Replace each code block with the highlighted version
7981
highlightedHTML := codeBlockRegex.ReplaceAllStringFunc(html, func(codeBlock string) string {
8082
// 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]
8285

8386
codeContent = stripBlockTags(codeContent)
8487

8588
// Highlight the code content
86-
highlightedCode := highlightSyntaxViaContent(codeContent)
89+
highlightedCode := highlightSyntaxViaContent(codeContent, lang)
8790

8891
// Replace the original code block with the highlighted version
8992
highlightedCodeBlock := "<pre>" + highlightedCode + "</pre>"

0 commit comments

Comments
 (0)