ansi.go 978 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package aec
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. const esc = "\x1b["
  7. // Reset resets SGR effect.
  8. const Reset string = "\x1b[0m"
  9. var empty = newAnsi("")
  10. // ANSI represents ANSI escape code.
  11. type ANSI interface {
  12. fmt.Stringer
  13. // With adapts given ANSIs.
  14. With(...ANSI) ANSI
  15. // Apply wraps given string in ANSI.
  16. Apply(string) string
  17. }
  18. type ansiImpl string
  19. func newAnsi(s string) *ansiImpl {
  20. r := ansiImpl(s)
  21. return &r
  22. }
  23. func (a *ansiImpl) With(ansi ...ANSI) ANSI {
  24. return concat(append([]ANSI{a}, ansi...))
  25. }
  26. func (a *ansiImpl) Apply(s string) string {
  27. return a.String() + s + Reset
  28. }
  29. func (a *ansiImpl) String() string {
  30. return string(*a)
  31. }
  32. // Apply wraps given string in ANSIs.
  33. func Apply(s string, ansi ...ANSI) string {
  34. if len(ansi) == 0 {
  35. return s
  36. }
  37. return concat(ansi).Apply(s)
  38. }
  39. func concat(ansi []ANSI) ANSI {
  40. strs := make([]string, 0, len(ansi))
  41. for _, p := range ansi {
  42. strs = append(strs, p.String())
  43. }
  44. return newAnsi(strings.Join(strs, ""))
  45. }