terminal256.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. # -*- coding: utf-8 -*-
  2. """
  3. pygments.formatters.terminal256
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. Formatter for 256-color terminal output with ANSI sequences.
  6. RGB-to-XTERM color conversion routines adapted from xterm256-conv
  7. tool (http://frexx.de/xterm-256-notes/data/xterm256-conv2.tar.bz2)
  8. by Wolfgang Frisch.
  9. Formatter version 1.
  10. :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
  11. :license: BSD, see LICENSE for details.
  12. """
  13. # TODO:
  14. # - Options to map style's bold/underline/italic/border attributes
  15. # to some ANSI attrbutes (something like 'italic=underline')
  16. # - An option to output "style RGB to xterm RGB/index" conversion table
  17. # - An option to indicate that we are running in "reverse background"
  18. # xterm. This means that default colors are white-on-black, not
  19. # black-on-while, so colors like "white background" need to be converted
  20. # to "white background, black foreground", etc...
  21. import sys
  22. from pygments.formatter import Formatter
  23. from pygments.console import codes
  24. from pygments.style import ansicolors
  25. __all__ = ['Terminal256Formatter', 'TerminalTrueColorFormatter']
  26. class EscapeSequence:
  27. def __init__(self, fg=None, bg=None, bold=False, underline=False):
  28. self.fg = fg
  29. self.bg = bg
  30. self.bold = bold
  31. self.underline = underline
  32. def escape(self, attrs):
  33. if len(attrs):
  34. return "\x1b[" + ";".join(attrs) + "m"
  35. return ""
  36. def color_string(self):
  37. attrs = []
  38. if self.fg is not None:
  39. if self.fg in ansicolors:
  40. esc = codes[self.fg.replace('ansi','')]
  41. if ';01m' in esc:
  42. self.bold = True
  43. # extract fg color code.
  44. attrs.append(esc[2:4])
  45. else:
  46. attrs.extend(("38", "5", "%i" % self.fg))
  47. if self.bg is not None:
  48. if self.bg in ansicolors:
  49. esc = codes[self.bg.replace('ansi','')]
  50. # extract fg color code, add 10 for bg.
  51. attrs.append(str(int(esc[2:4])+10))
  52. else:
  53. attrs.extend(("48", "5", "%i" % self.bg))
  54. if self.bold:
  55. attrs.append("01")
  56. if self.underline:
  57. attrs.append("04")
  58. return self.escape(attrs)
  59. def true_color_string(self):
  60. attrs = []
  61. if self.fg:
  62. attrs.extend(("38", "2", str(self.fg[0]), str(self.fg[1]), str(self.fg[2])))
  63. if self.bg:
  64. attrs.extend(("48", "2", str(self.bg[0]), str(self.bg[1]), str(self.bg[2])))
  65. if self.bold:
  66. attrs.append("01")
  67. if self.underline:
  68. attrs.append("04")
  69. return self.escape(attrs)
  70. def reset_string(self):
  71. attrs = []
  72. if self.fg is not None:
  73. attrs.append("39")
  74. if self.bg is not None:
  75. attrs.append("49")
  76. if self.bold or self.underline:
  77. attrs.append("00")
  78. return self.escape(attrs)
  79. class Terminal256Formatter(Formatter):
  80. """
  81. Format tokens with ANSI color sequences, for output in a 256-color
  82. terminal or console. Like in `TerminalFormatter` color sequences
  83. are terminated at newlines, so that paging the output works correctly.
  84. The formatter takes colors from a style defined by the `style` option
  85. and converts them to nearest ANSI 256-color escape sequences. Bold and
  86. underline attributes from the style are preserved (and displayed).
  87. .. versionadded:: 0.9
  88. .. versionchanged:: 2.2
  89. If the used style defines foreground colors in the form ``#ansi*``, then
  90. `Terminal256Formatter` will map these to non extended foreground color.
  91. See :ref:`AnsiTerminalStyle` for more information.
  92. .. versionchanged:: 2.4
  93. The ANSI color names have been updated with names that are easier to
  94. understand and align with colornames of other projects and terminals.
  95. See :ref:`this table <new-ansi-color-names>` for more information.
  96. Options accepted:
  97. `style`
  98. The style to use, can be a string or a Style subclass (default:
  99. ``'default'``).
  100. """
  101. name = 'Terminal256'
  102. aliases = ['terminal256', 'console256', '256']
  103. filenames = []
  104. def __init__(self, **options):
  105. Formatter.__init__(self, **options)
  106. self.xterm_colors = []
  107. self.best_match = {}
  108. self.style_string = {}
  109. self.usebold = 'nobold' not in options
  110. self.useunderline = 'nounderline' not in options
  111. self._build_color_table() # build an RGB-to-256 color conversion table
  112. self._setup_styles() # convert selected style's colors to term. colors
  113. def _build_color_table(self):
  114. # colors 0..15: 16 basic colors
  115. self.xterm_colors.append((0x00, 0x00, 0x00)) # 0
  116. self.xterm_colors.append((0xcd, 0x00, 0x00)) # 1
  117. self.xterm_colors.append((0x00, 0xcd, 0x00)) # 2
  118. self.xterm_colors.append((0xcd, 0xcd, 0x00)) # 3
  119. self.xterm_colors.append((0x00, 0x00, 0xee)) # 4
  120. self.xterm_colors.append((0xcd, 0x00, 0xcd)) # 5
  121. self.xterm_colors.append((0x00, 0xcd, 0xcd)) # 6
  122. self.xterm_colors.append((0xe5, 0xe5, 0xe5)) # 7
  123. self.xterm_colors.append((0x7f, 0x7f, 0x7f)) # 8
  124. self.xterm_colors.append((0xff, 0x00, 0x00)) # 9
  125. self.xterm_colors.append((0x00, 0xff, 0x00)) # 10
  126. self.xterm_colors.append((0xff, 0xff, 0x00)) # 11
  127. self.xterm_colors.append((0x5c, 0x5c, 0xff)) # 12
  128. self.xterm_colors.append((0xff, 0x00, 0xff)) # 13
  129. self.xterm_colors.append((0x00, 0xff, 0xff)) # 14
  130. self.xterm_colors.append((0xff, 0xff, 0xff)) # 15
  131. # colors 16..232: the 6x6x6 color cube
  132. valuerange = (0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff)
  133. for i in range(217):
  134. r = valuerange[(i // 36) % 6]
  135. g = valuerange[(i // 6) % 6]
  136. b = valuerange[i % 6]
  137. self.xterm_colors.append((r, g, b))
  138. # colors 233..253: grayscale
  139. for i in range(1, 22):
  140. v = 8 + i * 10
  141. self.xterm_colors.append((v, v, v))
  142. def _closest_color(self, r, g, b):
  143. distance = 257*257*3 # "infinity" (>distance from #000000 to #ffffff)
  144. match = 0
  145. for i in range(0, 254):
  146. values = self.xterm_colors[i]
  147. rd = r - values[0]
  148. gd = g - values[1]
  149. bd = b - values[2]
  150. d = rd*rd + gd*gd + bd*bd
  151. if d < distance:
  152. match = i
  153. distance = d
  154. return match
  155. def _color_index(self, color):
  156. index = self.best_match.get(color, None)
  157. if color in ansicolors:
  158. # strip the `ansi/#ansi` part and look up code
  159. index = color
  160. self.best_match[color] = index
  161. if index is None:
  162. try:
  163. rgb = int(str(color), 16)
  164. except ValueError:
  165. rgb = 0
  166. r = (rgb >> 16) & 0xff
  167. g = (rgb >> 8) & 0xff
  168. b = rgb & 0xff
  169. index = self._closest_color(r, g, b)
  170. self.best_match[color] = index
  171. return index
  172. def _setup_styles(self):
  173. for ttype, ndef in self.style:
  174. escape = EscapeSequence()
  175. # get foreground from ansicolor if set
  176. if ndef['ansicolor']:
  177. escape.fg = self._color_index(ndef['ansicolor'])
  178. elif ndef['color']:
  179. escape.fg = self._color_index(ndef['color'])
  180. if ndef['bgansicolor']:
  181. escape.bg = self._color_index(ndef['bgansicolor'])
  182. elif ndef['bgcolor']:
  183. escape.bg = self._color_index(ndef['bgcolor'])
  184. if self.usebold and ndef['bold']:
  185. escape.bold = True
  186. if self.useunderline and ndef['underline']:
  187. escape.underline = True
  188. self.style_string[str(ttype)] = (escape.color_string(),
  189. escape.reset_string())
  190. def format(self, tokensource, outfile):
  191. # hack: if the output is a terminal and has an encoding set,
  192. # use that to avoid unicode encode problems
  193. if not self.encoding and hasattr(outfile, "encoding") and \
  194. hasattr(outfile, "isatty") and outfile.isatty() and \
  195. sys.version_info < (3,):
  196. self.encoding = outfile.encoding
  197. return Formatter.format(self, tokensource, outfile)
  198. def format_unencoded(self, tokensource, outfile):
  199. for ttype, value in tokensource:
  200. not_found = True
  201. while ttype and not_found:
  202. try:
  203. # outfile.write( "<" + str(ttype) + ">" )
  204. on, off = self.style_string[str(ttype)]
  205. # Like TerminalFormatter, add "reset colors" escape sequence
  206. # on newline.
  207. spl = value.split('\n')
  208. for line in spl[:-1]:
  209. if line:
  210. outfile.write(on + line + off)
  211. outfile.write('\n')
  212. if spl[-1]:
  213. outfile.write(on + spl[-1] + off)
  214. not_found = False
  215. # outfile.write( '#' + str(ttype) + '#' )
  216. except KeyError:
  217. # ottype = ttype
  218. ttype = ttype[:-1]
  219. # outfile.write( '!' + str(ottype) + '->' + str(ttype) + '!' )
  220. if not_found:
  221. outfile.write(value)
  222. class TerminalTrueColorFormatter(Terminal256Formatter):
  223. r"""
  224. Format tokens with ANSI color sequences, for output in a true-color
  225. terminal or console. Like in `TerminalFormatter` color sequences
  226. are terminated at newlines, so that paging the output works correctly.
  227. .. versionadded:: 2.1
  228. Options accepted:
  229. `style`
  230. The style to use, can be a string or a Style subclass (default:
  231. ``'default'``).
  232. """
  233. name = 'TerminalTrueColor'
  234. aliases = ['terminal16m', 'console16m', '16m']
  235. filenames = []
  236. def _build_color_table(self):
  237. pass
  238. def _color_tuple(self, color):
  239. try:
  240. rgb = int(str(color), 16)
  241. except ValueError:
  242. return None
  243. r = (rgb >> 16) & 0xff
  244. g = (rgb >> 8) & 0xff
  245. b = rgb & 0xff
  246. return (r, g, b)
  247. def _setup_styles(self):
  248. for ttype, ndef in self.style:
  249. escape = EscapeSequence()
  250. if ndef['color']:
  251. escape.fg = self._color_tuple(ndef['color'])
  252. if ndef['bgcolor']:
  253. escape.bg = self._color_tuple(ndef['bgcolor'])
  254. if self.usebold and ndef['bold']:
  255. escape.bold = True
  256. if self.useunderline and ndef['underline']:
  257. escape.underline = True
  258. self.style_string[str(ttype)] = (escape.true_color_string(),
  259. escape.reset_string())