You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.0 KiB

  1. package chroma
  2. import (
  3. "io"
  4. )
  5. // A Formatter for Chroma lexers.
  6. type Formatter interface {
  7. // Format returns a formatting function for tokens.
  8. //
  9. // If the iterator panics, the Formatter should recover.
  10. Format(w io.Writer, style *Style, iterator Iterator) error
  11. }
  12. // A FormatterFunc is a Formatter implemented as a function.
  13. //
  14. // Guards against iterator panics.
  15. type FormatterFunc func(w io.Writer, style *Style, iterator Iterator) error
  16. func (f FormatterFunc) Format(w io.Writer, s *Style, it Iterator) (err error) { // nolint
  17. defer func() {
  18. if perr := recover(); perr != nil {
  19. err = perr.(error)
  20. }
  21. }()
  22. return f(w, s, it)
  23. }
  24. type recoveringFormatter struct {
  25. Formatter
  26. }
  27. func (r recoveringFormatter) Format(w io.Writer, s *Style, it Iterator) (err error) {
  28. defer func() {
  29. if perr := recover(); perr != nil {
  30. err = perr.(error)
  31. }
  32. }()
  33. return r.Formatter.Format(w, s, it)
  34. }
  35. // RecoveringFormatter wraps a formatter with panic recovery.
  36. func RecoveringFormatter(formatter Formatter) Formatter { return recoveringFormatter{formatter} }