feat: syntax highlighting for question codeblocks

This commit is contained in:
httpjamesm 2022-12-28 19:10:14 -05:00
parent 14b11b7f14
commit 96d4f768d9
2 changed files with 19 additions and 0 deletions

View File

@ -14,6 +14,7 @@ import (
)
var codeBlockRegex = regexp.MustCompile(`(?s)<pre><code>(.+?)<\/code><\/pre>`)
var questionCodeBlockRegex = regexp.MustCompile(`(?s)<pre class=".+"><code( class=".+")?>(.+?)</code></pre>`)
func ViewQuestion(c *gin.Context) {
client := resty.New()
@ -48,6 +49,20 @@ func ViewQuestion(c *gin.Context) {
panic(err)
}
// parse any code blocks and highlight them
answerCodeBlocks := questionCodeBlockRegex.FindAllString(questionBodyParentHTML, -1)
for _, codeBlock := range answerCodeBlocks {
codeBlock = utils.StripBlockTags(codeBlock)
fmt.Println(codeBlock)
// syntax highlight
highlightedCodeBlock := utils.HighlightSyntaxViaContent(codeBlock)
fmt.Println(highlightedCodeBlock)
// replace the code block with the highlighted code block
questionBodyParentHTML = strings.Replace(questionBodyParentHTML, codeBlock, highlightedCodeBlock, 1)
}
questionCard := doc.Find("div.postcell")
questionMetadata := questionCard.Find("div.user-info")

View File

@ -64,6 +64,8 @@ func HighlightSyntaxViaContent(content string) (htmlOut string) {
return
}
var preClassRegex = regexp.MustCompile(`(?s)<pre class=".+">`)
func StripBlockTags(content string) (result string) {
// strip all "<code>" tags
content = strings.Replace(content, "<code>", "", -1)
@ -72,6 +74,8 @@ func StripBlockTags(content string) (result string) {
content = strings.Replace(content, "<pre>", "", -1)
content = strings.Replace(content, "</pre>", "", -1)
content = preClassRegex.ReplaceAllString(content, "")
result = content
return