-
Notifications
You must be signed in to change notification settings - Fork 2
/
chroma.go
96 lines (79 loc) · 1.98 KB
/
chroma.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 main
// Building:
// go build -o chroma.so -buildmode=c-shared chroma.go
import "C"
import (
"bytes"
"github.com/alecthomas/chroma"
"github.com/alecthomas/chroma/formatters/html"
"github.com/alecthomas/chroma/lexers"
"github.com/alecthomas/chroma/quick"
"github.com/alecthomas/chroma/styles"
)
func main() {
}
// Highlight some text.
//
// Lexer, formatter and style may be empty, in which case a best-effort is made.
//export highlight
func highlight(source, lexer, formatter, style string) *C.char {
writer := new(bytes.Buffer)
quick.Highlight(writer, source, lexer, formatter, style)
return C.CString(writer.String())
}
// Highlight some text.
//
//export highlightAsHtml
func highlightAsHtml(source, lexer, style string, htmlTabWidthFlag int, htmlBaseLineFlag int,
htmlPrefixFlag string, htmlLinesTableFlag bool, htmlLinesFlag bool, htmlOnlyFlag bool,
htmlInlineStyleFlag bool, htmlStylesFlag bool) *C.char {
// Writer
w := new(bytes.Buffer)
// Lexer
l := lexers.Get(lexer)
if l == nil {
l = lexers.Analyse(source)
}
if l == nil {
l = lexers.Fallback
}
l = chroma.Coalesce(l)
// Determine style.
s := styles.Get(style)
if s == nil {
s = styles.Fallback
}
// Formatter options
options := []html.Option{
html.TabWidth(htmlTabWidthFlag),
html.BaseLineNumber(htmlBaseLineFlag),
}
if htmlPrefixFlag != "" {
options = append(options, html.ClassPrefix(htmlPrefixFlag))
}
if htmlStylesFlag {
// Dump styles.
formatter := html.New(html.WithClasses())
formatter.WriteCSS(w, s)
return C.CString(w.String())
}
if !htmlInlineStyleFlag {
options = append(options, html.WithClasses())
}
if !htmlOnlyFlag {
options = append(options, html.Standalone())
}
if htmlLinesFlag {
options = append(options, html.WithLineNumbers())
}
if htmlLinesTableFlag {
options = append(options, html.LineNumbersInTable())
}
f := html.New(options...)
it, err := l.Tokenise(nil, source)
if err != nil {
return nil
}
f.Format(w, s, it)
return C.CString(w.String())
}