terminal256.py 11 KB

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