style.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package style
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. // TODO: at some point I need to sanitize preexisting escape codes
  7. // in input, to do so replace the escape character with visual
  8. // escape character
  9. /*
  10. To, e.g., bold, prepend the bold character,
  11. then substitute all resets with `${reset}${bold}`
  12. to force rebold after all resets, to make sure. Might
  13. be complex with layering
  14. */
  15. // const (
  16. // Bold =
  17. // )
  18. func Background(text string, r uint8, g uint8, b uint8) string {
  19. setter := fmt.Sprintf("\x1b[48;2;%d;%d;%dm", r, g, b)
  20. resetter := "\x1b[49m"
  21. text = strings.ReplaceAll(text, resetter, setter)
  22. return fmt.Sprintf("%s%s%s", setter, text, resetter)
  23. }
  24. func ExtendBackground(text string) string {
  25. return strings.ReplaceAll(text, "\n", "\x1b[K\n")
  26. }
  27. func Foreground(text string, r uint8, g uint8, b uint8) string {
  28. setter := fmt.Sprintf("\x1b[38;2;%d;%d;%dm", r, g, b)
  29. resetter := "\x1b[39m"
  30. newText := strings.ReplaceAll(text, resetter, setter)
  31. return fmt.Sprintf("%s%s%s", setter, newText, resetter)
  32. }
  33. func Display(text string, prependCode int, appendCode int) string {
  34. return fmt.Sprintf("\x1b[%dm%s\x1b[%dm", prependCode, text, appendCode)
  35. }
  36. // 21 doesn't work (does double underline)
  37. // 22 removes bold and faint, faint is never used
  38. // so it does the job
  39. func Bold(text string) string {
  40. return Display(text, 1, 22)
  41. }
  42. func Strikethrough(text string) string {
  43. return Display(text, 9, 29)
  44. }
  45. func Underline(text string) string {
  46. return Display(text, 4, 24)
  47. }
  48. func Italic(text string) string {
  49. return Display(text, 3, 23)
  50. }
  51. func Code(text string) string {
  52. return Background(text, 75, 75, 75)
  53. }
  54. func CodeBlock(text string) string {
  55. return ExtendBackground(Code(text))
  56. }
  57. func Highlight(text string) string {
  58. return Background(text, 13, 125, 0)
  59. }
  60. func Color(text string) string {
  61. return Foreground(text, 164, 245, 155)
  62. }
  63. func Linkify(text string) string {
  64. return Underline(Color(text))
  65. }
  66. // func Underline(text string) string {
  67. // return Display(text, )
  68. // }
  69. // func Anchor(text string) string {
  70. // }