api.go

 1package formatters
 2
 3import (
 4	"io"
 5	"sort"
 6
 7	"github.com/alecthomas/chroma"
 8	"github.com/alecthomas/chroma/formatters/html"
 9	"github.com/alecthomas/chroma/formatters/svg"
10)
11
12var (
13	// NoOp formatter.
14	NoOp = Register("noop", chroma.FormatterFunc(func(w io.Writer, s *chroma.Style, iterator chroma.Iterator) error {
15		for t := iterator(); t != chroma.EOF; t = iterator() {
16			if _, err := io.WriteString(w, t.Value); err != nil {
17				return err
18			}
19		}
20		return nil
21	}))
22	// Default HTML formatter outputs self-contained HTML.
23	htmlFull = Register("html", html.New(html.Standalone(true), html.WithClasses(true))) // nolint
24	SVG      = Register("svg", svg.New(svg.EmbedFont("Liberation Mono", svg.FontLiberationMono, svg.WOFF)))
25)
26
27// Fallback formatter.
28var Fallback = NoOp
29
30// Registry of Formatters.
31var Registry = map[string]chroma.Formatter{}
32
33// Names of registered formatters.
34func Names() []string {
35	out := []string{}
36	for name := range Registry {
37		out = append(out, name)
38	}
39	sort.Strings(out)
40	return out
41}
42
43// Get formatter by name.
44//
45// If the given formatter is not found, the Fallback formatter will be returned.
46func Get(name string) chroma.Formatter {
47	if f, ok := Registry[name]; ok {
48		return f
49	}
50	return Fallback
51}
52
53// Register a named formatter.
54func Register(name string, formatter chroma.Formatter) chroma.Formatter {
55	Registry[name] = formatter
56	return formatter
57}