terminal256.py 11 KB

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