Antonio Mika
·
31 May 24
parser.go
1package pastes
2
3import (
4 "bytes"
5
6 "github.com/alecthomas/chroma/v2/formatters/html"
7 "github.com/alecthomas/chroma/v2/lexers"
8 "github.com/alecthomas/chroma/v2/styles"
9)
10
11func ParseText(filename string, text string) (string, error) {
12 formatter := html.New(
13 html.WithLineNumbers(true),
14 html.WithLinkableLineNumbers(true, ""),
15 html.WithClasses(true),
16 )
17 lexer := lexers.Match(filename)
18 if lexer == nil {
19 lexer = lexers.Analyse(text)
20 }
21 if lexer == nil {
22 lexer = lexers.Get("plaintext")
23 }
24 iterator, err := lexer.Tokenise(nil, text)
25 if err != nil {
26 return text, err
27 }
28 var buf bytes.Buffer
29 err = formatter.Format(&buf, styles.Get("dracula"), iterator)
30 if err != nil {
31 return text, err
32 }
33 return buf.String(), nil
34}