1. package formatters
    
  2. 
    
  3. import (
    
  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.
    
  12. var JSON = Register("json", chroma.FormatterFunc(func(w io.Writer, s *chroma.Style, it chroma.Iterator) error {
    
  13. 	fmt.Fprintln(w, "[")
    
  14. 	i := 0
    
  15. 	for t := it(); t != chroma.EOF; t = it() {
    
  16. 		if i > 0 {
    
  17. 			fmt.Fprintln(w, ",")
    
  18. 		}
    
  19. 		i++
    
  20. 		bytes, err := json.Marshal(t)
    
  21. 		if err != nil {
    
  22. 			return err
    
  23. 		}
    
  24. 		if _, err := fmt.Fprint(w, "  "+string(bytes)); err != nil {
    
  25. 			return err
    
  26. 		}
    
  27. 	}
    
  28. 	fmt.Fprintln(w)
    
  29. 	fmt.Fprintln(w, "]")
    
  30. 	return nil
    
  31. }))