mirror of
https://github.com/alecthomas/chroma.git
synced 2025-03-17 20:58:08 +02:00
This is to solve an issue where writers returned by the Formatter were often stateful, but this fact was not obvious to the API consumer, and failed in interesting ways.
44 lines
814 B
Go
44 lines
814 B
Go
package quick
|
|
|
|
import (
|
|
"io"
|
|
|
|
"github.com/alecthomas/chroma"
|
|
"github.com/alecthomas/chroma/formatters"
|
|
"github.com/alecthomas/chroma/lexers"
|
|
"github.com/alecthomas/chroma/styles"
|
|
)
|
|
|
|
// Highlight some text.
|
|
//
|
|
// Lexer, formatter and style may be empty, in which case a best-effort is made.
|
|
func Highlight(w io.Writer, source, lexer, formatter, style string) error {
|
|
// Determine lexer.
|
|
l := lexers.Get(lexer)
|
|
if l == nil {
|
|
l = lexers.Analyse(source)
|
|
}
|
|
if l == nil {
|
|
l = lexers.Fallback
|
|
}
|
|
l = chroma.Coalesce(l)
|
|
|
|
// Determine formatter.
|
|
f := formatters.Get(formatter)
|
|
if f == nil {
|
|
f = formatters.Fallback
|
|
}
|
|
|
|
// Determine style.
|
|
s := styles.Get(style)
|
|
if s == nil {
|
|
s = styles.Fallback
|
|
}
|
|
|
|
it, err := l.Tokenise(nil, source)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return f.Format(w, s, it)
|
|
}
|