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