terminal256.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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-2017 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[5:]]
  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[5:]]
  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. Options accepted:
  93. `style`
  94. The style to use, can be a string or a Style subclass (default:
  95. ``'default'``).
  96. """
  97. name = 'Terminal256'
  98. aliases = ['terminal256', 'console256', '256']
  99. filenames = []
  100. def __init__(self, **options):
  101. Formatter.__init__(self, **options)
  102. self.xterm_colors = []
  103. self.best_match = {}
  104. self.style_string = {}
  105. self.usebold = 'nobold' not in options
  106. self.useunderline = 'nounderline' not in options
  107. self._build_color_table() # build an RGB-to-256 color conversion table
  108. self._setup_styles() # convert selected style's colors to term. colors
  109. def _build_color_table(self):
  110. # colors 0..15: 16 basic colors
  111. self.xterm_colors.append((0x00, 0x00, 0x00)) # 0
  112. self.xterm_colors.append((0xcd, 0x00, 0x00)) # 1
  113. self.xterm_colors.append((0x00, 0xcd, 0x00)) # 2
  114. self.xterm_colors.append((0xcd, 0xcd, 0x00)) # 3
  115. self.xterm_colors.append((0x00, 0x00, 0xee)) # 4
  116. self.xterm_colors.append((0xcd, 0x00, 0xcd)) # 5
  117. self.xterm_colors.append((0x00, 0xcd, 0xcd)) # 6
  118. self.xterm_colors.append((0xe5, 0xe5, 0xe5)) # 7
  119. self.xterm_colors.append((0x7f, 0x7f, 0x7f)) # 8
  120. self.xterm_colors.append((0xff, 0x00, 0x00)) # 9
  121. self.xterm_colors.append((0x00, 0xff, 0x00)) # 10
  122. self.xterm_colors.append((0xff, 0xff, 0x00)) # 11
  123. self.xterm_colors.append((0x5c, 0x5c, 0xff)) # 12
  124. self.xterm_colors.append((0xff, 0x00, 0xff)) # 13
  125. self.xterm_colors.append((0x00, 0xff, 0xff)) # 14
  126. self.xterm_colors.append((0xff, 0xff, 0xff)) # 15
  127. # colors 16..232: the 6x6x6 color cube
  128. valuerange = (0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff)
  129. for i in range(217):
  130. r = valuerange[(i // 36) % 6]
  131. g = valuerange[(i // 6) % 6]
  132. b = valuerange[i % 6]
  133. self.xterm_colors.append((r, g, b))
  134. # colors 233..253: grayscale
  135. for i in range(1, 22):
  136. v = 8 + i * 10
  137. self.xterm_colors.append((v, v, v))
  138. def _closest_color(self, r, g, b):
  139. distance = 257*257*3 # "infinity" (>distance from #000000 to #ffffff)
  140. match = 0
  141. for i in range(0, 254):
  142. values = self.xterm_colors[i]
  143. rd = r - values[0]
  144. gd = g - values[1]
  145. bd = b - values[2]
  146. d = rd*rd + gd*gd + bd*bd
  147. if d < distance:
  148. match = i
  149. distance = d
  150. return match
  151. def _color_index(self, color):
  152. index = self.best_match.get(color, None)
  153. if color in ansicolors:
  154. # strip the `#ansi` part and look up code
  155. index = color
  156. self.best_match[color] = index
  157. if index is None:
  158. try:
  159. rgb = int(str(color), 16)
  160. except ValueError:
  161. rgb = 0
  162. r = (rgb >> 16) & 0xff
  163. g = (rgb >> 8) & 0xff
  164. b = rgb & 0xff
  165. index = self._closest_color(r, g, b)
  166. self.best_match[color] = index
  167. return index
  168. def _setup_styles(self):
  169. for ttype, ndef in self.style:
  170. escape = EscapeSequence()
  171. # get foreground from ansicolor if set
  172. if ndef['ansicolor']:
  173. escape.fg = self._color_index(ndef['ansicolor'])
  174. elif ndef['color']:
  175. escape.fg = self._color_index(ndef['color'])
  176. if ndef['bgansicolor']:
  177. escape.bg = self._color_index(ndef['bgansicolor'])
  178. elif ndef['bgcolor']:
  179. escape.bg = self._color_index(ndef['bgcolor'])
  180. if self.usebold and ndef['bold']:
  181. escape.bold = True
  182. if self.useunderline and ndef['underline']:
  183. escape.underline = True
  184. self.style_string[str(ttype)] = (escape.color_string(),
  185. escape.reset_string())
  186. def format(self, tokensource, outfile):
  187. # hack: if the output is a terminal and has an encoding set,
  188. # use that to avoid unicode encode problems
  189. if not self.encoding and hasattr(outfile, "encoding") and \
  190. hasattr(outfile, "isatty") and outfile.isatty() and \
  191. sys.version_info < (3,):
  192. self.encoding = outfile.encoding
  193. return Formatter.format(self, tokensource, outfile)
  194. def format_unencoded(self, tokensource, outfile):
  195. for ttype, value in tokensource:
  196. not_found = True
  197. while ttype and not_found:
  198. try:
  199. # outfile.write( "<" + str(ttype) + ">" )
  200. on, off = self.style_string[str(ttype)]
  201. # Like TerminalFormatter, add "reset colors" escape sequence
  202. # on newline.
  203. spl = value.split('\n')
  204. for line in spl[:-1]:
  205. if line:
  206. outfile.write(on + line + off)
  207. outfile.write('\n')
  208. if spl[-1]:
  209. outfile.write(on + spl[-1] + off)
  210. not_found = False
  211. # outfile.write( '#' + str(ttype) + '#' )
  212. except KeyError:
  213. # ottype = ttype
  214. ttype = ttype[:-1]
  215. # outfile.write( '!' + str(ottype) + '->' + str(ttype) + '!' )
  216. if not_found:
  217. outfile.write(value)
  218. class TerminalTrueColorFormatter(Terminal256Formatter):
  219. r"""
  220. Format tokens with ANSI color sequences, for output in a true-color
  221. terminal or console. Like in `TerminalFormatter` color sequences
  222. are terminated at newlines, so that paging the output works correctly.
  223. .. versionadded:: 2.1
  224. Options accepted:
  225. `style`
  226. The style to use, can be a string or a Style subclass (default:
  227. ``'default'``).
  228. """
  229. name = 'TerminalTrueColor'
  230. aliases = ['terminal16m', 'console16m', '16m']
  231. filenames = []
  232. def _build_color_table(self):
  233. pass
  234. def _color_tuple(self, color):
  235. try:
  236. rgb = int(str(color), 16)
  237. except ValueError:
  238. return None
  239. r = (rgb >> 16) & 0xff
  240. g = (rgb >> 8) & 0xff
  241. b = rgb & 0xff
  242. return (r, g, b)
  243. def _setup_styles(self):
  244. for ttype, ndef in self.style:
  245. escape = EscapeSequence()
  246. if ndef['color']:
  247. escape.fg = self._color_tuple(ndef['color'])
  248. if ndef['bgcolor']:
  249. escape.bg = self._color_tuple(ndef['bgcolor'])
  250. if self.usebold and ndef['bold']:
  251. escape.bold = True
  252. if self.useunderline and ndef['underline']:
  253. escape.underline = True
  254. self.style_string[str(ttype)] = (escape.true_color_string(),
  255. escape.reset_string())