源码 | 翻译 |
---|---|
github repo | 中文 |
要是屁话,不想听,直接上例子,或看中文翻译
lexers
词法分析器
styles
主题/样式[
abap, algol, algol_nu, arduino, autumn, borland, bw, colorful, dracula, emacs, friendly, fruity, github, igor, lovelace, manni, monokai, monokailight, murphy, native, paraiso-dark, paraiso-light, pastie, perldoc, pygments, rainbow_dash, rrt, solarized-dark, solarized-dark256, solarized-light, swapoff, tango, trac, vim, vsxcode
]
formatters
格式化/+高亮吧[ html, json, noop, terminal, terminal16m, terminal256, tokens ]
1. chroma lexers
2. chroma styles
3. chroma formatters
package main
import (
"bytes"
"fmt"
"log"
"github.com/alecthomas/chroma/formatters"
"github.com/alecthomas/chroma/lexers"
"github.com/alecthomas/chroma/quick"
"github.com/alecthomas/chroma/styles"
)
func main() {
// 源码
s := `package main
import (
"fmt"
)
func main() {
fmt.Println("Hello, playground")
}
`
res := colorCode(s) // example 返回,高亮字符
fmt.Println(res)
}
// 接 下面的 example-*
quick.Highlight
输出
func colorCode(s string) string {
res := new(bytes.Buffer) // 放 高亮的字符
style := styles.Get("dark") // 主题设置
if style == nil {
fmt.Println(style)
style = styles.Fallback // 默认主题
}
attr := "terminal" // 终端
formatter := formatters.Get(attr) // 环境的变量,默认为`html`
if formatter == nil {
formatter = formatters.Fallback // 默认格式化
}
err := quick.Highlight(res, s, "go", attr, style.Name) // 直接高亮
// 1. 放哪,2. 源码,3. 语言,4. 格式环境,5. 主题名
if err != nil {
log.Fatalln(err)
}
return res.String()
}
formatter.Format
输出
func colorCode(s string) string {
res := new(bytes.Buffer)
lexer := lexers.Get("go")
if lexer == nil {
lexer = lexers.Fallback
}
style := styles.Get("dracula")
if style == nil {
style = styles.Fallback
}
// [html json noop terminal terminal16m terminal256 tokens]
formatter := formatters.Get("terminal")
if formatter == nil {
formatter = formatters.Fallback
}
iterator, err := lexer.Tokenise(nil, s) // 拿到迭代器
err = formatter.Format(res, style, iterator)
if err != nil {
log.Fatalln(err)
}
return res.String()
}