package utils import ( "bytes" "html" "io" "regexp" "strings" "github.com/alecthomas/chroma/formatters" "github.com/alecthomas/chroma/lexers" "github.com/alecthomas/chroma/styles" ) var plainFormattedCodeRegex = regexp.MustCompile(`(?s)
(.+?)
`)
func HighlightSyntaxViaContent(content string) (htmlOut string) {
content = html.UnescapeString(content)
fallbackOut := html.EscapeString(content)
// identify the language
lexer := lexers.Analyse(content)
if lexer == nil {
// unable to identify, so just return the wrapped content
htmlOut = fallbackOut
return
}
style := styles.Get("xcode")
if style == nil {
style = styles.Fallback
}
formatter := formatters.Get("html")
if formatter == nil {
formatter = formatters.Fallback
}
iterator, err := lexer.Tokenise(nil, content)
if err != nil {
htmlOut = fallbackOut
return
}
b := bytes.NewBufferString("")
w := io.Writer(b)
err = formatter.Format(w, style, iterator)
if err != nil {
htmlOut = fallbackOut
return
}
// parse only the ...
part
htmlOut = b.String()
htmlOut = plainFormattedCodeRegex.FindString(htmlOut)
htmlOut = StripBlockTags(htmlOut)
// remove htmlOut = strings.Replace(htmlOut, "", "", -1) return } var preClassRegex = regexp.MustCompile(`(?s)`) func StripBlockTags(content string) (result string) { // strip all "" tags content = strings.Replace(content, "
", "", -1) content = strings.Replace(content, "
", "", -1) // and thecontent = strings.Replace(content, "", "", -1) content = strings.Replace(content, "", "", -1) content = preClassRegex.ReplaceAllString(content, "") result = content return }