console.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """
  2. pygments.console
  3. ~~~~~~~~~~~~~~~~
  4. Format colored console output.
  5. :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
  6. :license: BSD, see LICENSE for details.
  7. """
  8. esc = "\x1b["
  9. codes = {}
  10. codes[""] = ""
  11. codes["reset"] = esc + "39;49;00m"
  12. codes["bold"] = esc + "01m"
  13. codes["faint"] = esc + "02m"
  14. codes["standout"] = esc + "03m"
  15. codes["underline"] = esc + "04m"
  16. codes["blink"] = esc + "05m"
  17. codes["overline"] = esc + "06m"
  18. dark_colors = ["black", "red", "green", "yellow", "blue",
  19. "magenta", "cyan", "gray"]
  20. light_colors = ["brightblack", "brightred", "brightgreen", "brightyellow", "brightblue",
  21. "brightmagenta", "brightcyan", "white"]
  22. x = 30
  23. for dark, light in zip(dark_colors, light_colors):
  24. codes[dark] = esc + "%im" % x
  25. codes[light] = esc + "%im" % (60 + x)
  26. x += 1
  27. del dark, light, x
  28. codes["white"] = codes["bold"]
  29. def reset_color():
  30. return codes["reset"]
  31. def colorize(color_key, text):
  32. return codes[color_key] + text + codes["reset"]
  33. def ansiformat(attr, text):
  34. """
  35. Format ``text`` with a color and/or some attributes::
  36. color normal color
  37. *color* bold color
  38. _color_ underlined color
  39. +color+ blinking color
  40. """
  41. result = []
  42. if attr[:1] == attr[-1:] == '+':
  43. result.append(codes['blink'])
  44. attr = attr[1:-1]
  45. if attr[:1] == attr[-1:] == '*':
  46. result.append(codes['bold'])
  47. attr = attr[1:-1]
  48. if attr[:1] == attr[-1:] == '_':
  49. result.append(codes['underline'])
  50. attr = attr[1:-1]
  51. result.append(codes[attr])
  52. result.append(text)
  53. result.append(codes['reset'])
  54. return ''.join(result)