~erock/pico

pico/pastes/parser.go -rw-r--r-- 718 bytes
0c813f80Eric Bower chore: reference github instead of sr.ht 14 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package pastes

import (
	"bytes"

	"github.com/alecthomas/chroma/formatters/html"
	"github.com/alecthomas/chroma/lexers"
	"github.com/alecthomas/chroma/styles"
)

func ParseText(filename string, text string) (string, error) {
	formatter := html.New(
		html.WithLineNumbers(true),
		html.LinkableLineNumbers(true, ""),
		html.WithClasses(true),
	)
	lexer := lexers.Match(filename)
	if lexer == nil {
		lexer = lexers.Analyse(text)
	}
	if lexer == nil {
		lexer = lexers.Get("plaintext")
	}
	iterator, err := lexer.Tokenise(nil, text)
	if err != nil {
		return text, err
	}
	var buf bytes.Buffer
	err = formatter.Format(&buf, styles.Dracula, iterator)
	if err != nil {
		return text, err
	}
	return buf.String(), nil
}