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.

ansi.go 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package pretty
  2. import (
  3. "bytes"
  4. )
  5. type Code string
  6. type Codes []Code
  7. type Effect interface {
  8. E(string) string
  9. }
  10. // Empty effect
  11. type nilEffect struct{}
  12. func (_ nilEffect) E(x string) string { return x }
  13. // Custom effect
  14. type customEffect func(string) string
  15. func (e customEffect) E(x string) string { return e(x) }
  16. const (
  17. RESET = Code("0")
  18. BOLD = Code("1")
  19. DIM = Code("2")
  20. ITALIC = Code("3")
  21. UNDERL = Code("4")
  22. INV = Code("7")
  23. HIDDEN = Code("8")
  24. STRIKE = Code("9")
  25. BLACK = Code("30")
  26. RED = Code("31")
  27. GREEN = Code("32")
  28. YELLOW = Code("33")
  29. BLUE = Code("34")
  30. MGNTA = Code("35")
  31. CYAN = Code("36")
  32. WHITE = Code("37")
  33. HBLACK = Code("90")
  34. HRED = Code("91")
  35. HGREEN = Code("92")
  36. HYELLOW = Code("93")
  37. HBLUE = Code("94")
  38. HMGNTA = Code("95")
  39. HCYAN = Code("96")
  40. HWHITE = Code("97")
  41. )
  42. func Add(x... Code) Codes {
  43. return Codes(x)
  44. }
  45. func (c Code) E(x string) string {
  46. if !isTTY { return x }
  47. return "\x1b[" + string(c) + "m" + x + "\x1b[0m"
  48. }
  49. func (cs Codes) E(x string) string {
  50. if !isTTY { return x }
  51. var b bytes.Buffer
  52. b.WriteString("\x1b[")
  53. for _, c := range cs {
  54. b.WriteRune(';')
  55. b.WriteString(string(c))
  56. }
  57. b.WriteRune('m')
  58. b.WriteString(x)
  59. b.WriteString("\x1b[0m")
  60. return b.String()
  61. }
  62. func Wrap(e Effect, wrapper string) Effect {
  63. if !isTTY { return nilEffect{} }
  64. return customEffect(func(s string) string {
  65. return e.E(wrapper[0:1]) + s + e.E(wrapper[1:2])
  66. })
  67. }