-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsyntax.go
96 lines (79 loc) · 2.05 KB
/
syntax.go
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package util
import (
"bytes"
"io"
"io/ioutil"
"github.com/alecthomas/chroma"
"github.com/alecthomas/chroma/formatters/html"
"github.com/alecthomas/chroma/lexers"
)
func getFormatter() *html.Formatter {
return html.New(html.TabWidth(4), html.WithClasses(),
html.WithLineNumbers(), html.LineNumbersInTable())
}
func getStyle() (*chroma.Style, error) {
style, err := chroma.NewStyle("ayu-dark", chroma.StyleEntries{
chroma.Background: " bg:#0a0e14",
chroma.Text: "#b3b1ad",
chroma.Comment: "#626a73",
chroma.Error: "#ff3333",
chroma.GenericDeleted: "#d96c75",
chroma.GenericInserted: "#91b362",
chroma.Keyword: "#ff8f40",
chroma.KeywordConstant: "#ffee99",
chroma.KeywordType: "#39bae6",
chroma.LiteralNumber: "#ffee99",
chroma.LiteralString: "#c2d94c",
chroma.LiteralStringChar: "#95e6cb",
chroma.LiteralStringOther: "#95e6cb",
chroma.LiteralStringRegex: "#95e6cb",
chroma.NameAttribute: "#ffb454",
chroma.NameClass: "#ffb454",
chroma.NameDecorator: "#e6b673",
chroma.NameNamespace: "#ffb454",
chroma.NameTag: "#39bae6",
chroma.OperatorWord: "#f29668",
})
if err != nil {
return nil, err
}
return style, nil
}
func Highlight(filename string, r io.ReadCloser) (string, error) {
b, err := ioutil.ReadAll(r)
if err != nil {
return "", err
}
contents := string(b)
lexer := lexers.Match(filename)
if lexer == nil {
lexer = lexers.Analyse(contents)
}
if lexer == nil {
lexer = lexers.Fallback
}
style, err := getStyle()
if err != nil {
return "", err
}
iterator, err := lexer.Tokenise(nil, contents)
if err != nil {
return "", err
}
buffer := new(bytes.Buffer)
formatter := getFormatter()
err = formatter.Format(buffer, style, iterator)
if err != nil {
return "", err
}
return buffer.String(), nil
}
func WriteCSS(w io.Writer) error {
style, err := getStyle()
if err != nil {
return err
}
formatter := getFormatter()
err = formatter.WriteCSS(w, style)
return err
}