color.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. package color
  2. import (
  3. "strconv"
  4. "strings"
  5. )
  6. const (
  7. csi = "\x1b["
  8. Clear = "\x1b[0m"
  9. )
  10. type Attribute int
  11. // https://en.wikipedia.org/wiki/ANSI_escape_code
  12. const (
  13. Reset Attribute = iota
  14. Bold
  15. Faint
  16. Italic
  17. Underline
  18. SlowBlink
  19. RapidBlink
  20. ReverseVideo
  21. Conceal
  22. CrossedOut
  23. )
  24. const (
  25. 重置 Attribute = iota
  26. 加粗
  27. 弱化
  28. 斜体
  29. 下划线
  30. 缓慢闪烁
  31. 快速闪烁
  32. 反显
  33. 消隐
  34. 划除
  35. )
  36. type Color int
  37. const (
  38. Black Color = iota + 30
  39. Red
  40. Green
  41. Yellow
  42. Blue
  43. Magenta
  44. Cyan
  45. White
  46. )
  47. type Sequence []Attribute
  48. func (seq Sequence) String() string {
  49. var b strings.Builder
  50. b.WriteString(csi)
  51. if len(seq) > 0 {
  52. b.WriteString(strconv.Itoa(int(seq[0])))
  53. }
  54. for _, v := range seq[1:] {
  55. b.WriteRune(';')
  56. b.WriteString(strconv.Itoa(int(v)))
  57. }
  58. b.WriteRune('m')
  59. return b.String()
  60. }
  61. func (seq Sequence) Base(attrs ...Attribute) Sequence {
  62. return append(seq, attrs...)
  63. }
  64. func (seq Sequence) Bg(c Color) Sequence {
  65. return append(seq, add(c, 10))
  66. }
  67. func (seq Sequence) Fg(c Color) Sequence {
  68. return append(seq, Attribute(c))
  69. }
  70. func (seq Sequence) Hi(c Color) Sequence {
  71. return append(seq, add(c, 60))
  72. }
  73. func (seq Sequence) HiBg(c Color) Sequence {
  74. return append(seq, add(c, 70))
  75. }
  76. func (seq Sequence) BgRGB(r, g, b int) Sequence {
  77. return append(seq, Sequence{48, 2, Attribute(r), Attribute(g), Attribute(b)}...)
  78. }
  79. func (seq Sequence) FgRGB(r, g, b int) Sequence {
  80. return append(seq, Sequence{38, 2, Attribute(r), Attribute(g), Attribute(b)}...)
  81. }
  82. func Base(attrs ...Attribute) Sequence {
  83. return Sequence(attrs)
  84. }
  85. func Bg(c Color) Sequence {
  86. return []Attribute{add(c, 10)}
  87. }
  88. func Fg(c Color) Sequence {
  89. return []Attribute{Attribute(c)}
  90. }
  91. func Hi(c Color) Sequence {
  92. return []Attribute{add(c, 60)}
  93. }
  94. func HiBg(c Color) Sequence {
  95. return []Attribute{add(c, 70)}
  96. }
  97. func add(c Color, offset int) Attribute {
  98. return Attribute(c) + Attribute(offset)
  99. }