terminal256.py 11 KB

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