1package formatters
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7
8 "github.com/alecthomas/chroma/v2"
9)
10
11// JSON formatter outputs the raw token structures as JSON.
12var JSON = Register("json", chroma.FormatterFunc(func(w io.Writer, s *chroma.Style, it chroma.Iterator) error {
13 if _, err := fmt.Fprintln(w, "["); err != nil {
14 return err
15 }
16 i := 0
17 for t := it(); t != chroma.EOF; t = it() {
18 if i > 0 {
19 if _, err := fmt.Fprintln(w, ","); err != nil {
20 return err
21 }
22 }
23 i++
24 bytes, err := json.Marshal(t)
25 if err != nil {
26 return err
27 }
28 if _, err := fmt.Fprint(w, " "+string(bytes)); err != nil {
29 return err
30 }
31 }
32 if _, err := fmt.Fprintln(w); err != nil {
33 return err
34 }
35 if _, err := fmt.Fprintln(w, "]"); err != nil {
36 return err
37 }
38 return nil
39}))