/console/app/pygments/formatters/terminal256.py

https://bitbucket.org/alex_muscar/myspace-competition-radar · Python · 221 lines · 140 code · 31 blank · 50 comment · 39 complexity · 884f026dfc770060db4fcdf11027beb9 MD5 · raw file

  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: 2007 by Artem Egorkine.
  11. :license: BSD, see LICENSE for more 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. from pygments.formatter import Formatter
  22. __all__ = ['Terminal256Formatter']
  23. class EscapeSequence:
  24. def __init__(self, fg=None, bg=None, bold=False, underline=False):
  25. self.fg = fg
  26. self.bg = bg
  27. self.bold = bold
  28. self.underline = underline
  29. def escape(self, attrs):
  30. if len(attrs):
  31. return "\x1b[" + ";".join(attrs) + "m"
  32. return ""
  33. def color_string(self):
  34. attrs = []
  35. if self.fg is not None:
  36. attrs.extend(("38", "5", "%i" % self.fg))
  37. if self.bg is not None:
  38. attrs.extend(("48", "5", "%i" % self.bg))
  39. if self.bold:
  40. attrs.append("01")
  41. if self.underline:
  42. attrs.append("04")
  43. return self.escape(attrs)
  44. def reset_string(self):
  45. attrs = []
  46. if self.fg is not None:
  47. attrs.append("39")
  48. if self.bg is not None:
  49. attrs.append("49")
  50. if self.bold or self.underline:
  51. attrs.append("00")
  52. return self.escape(attrs)
  53. class Terminal256Formatter(Formatter):
  54. r"""
  55. Format tokens with ANSI color sequences, for output in a 256-color
  56. terminal or console. Like in `TerminalFormatter` color sequences
  57. are terminated at newlines, so that paging the output works correctly.
  58. The formatter takes colors from a style defined by the `style` option
  59. and converts them to nearest ANSI 256-color escape sequences. Bold and
  60. underline attributes from the style are preserved (and displayed).
  61. *New in Pygments 0.9.*
  62. Options accepted:
  63. `style`
  64. The style to use, can be a string or a Style subclass (default:
  65. ``'default'``).
  66. """
  67. name = 'Terminal256'
  68. aliases = ['terminal256', 'console256', '256']
  69. filenames = []
  70. def __init__(self, **options):
  71. Formatter.__init__(self, **options)
  72. self.xterm_colors = []
  73. self.best_match = {}
  74. self.style_string = {}
  75. self.usebold = 'nobold' not in options
  76. self.useunderline = 'nounderline' not in options
  77. self._build_color_table() # build an RGB-to-256 color conversion table
  78. self._setup_styles() # convert selected style's colors to term. colors
  79. def _build_color_table(self):
  80. # colors 0..15: 16 basic colors
  81. self.xterm_colors.append((0x00, 0x00, 0x00)) # 0
  82. self.xterm_colors.append((0xcd, 0x00, 0x00)) # 1
  83. self.xterm_colors.append((0x00, 0xcd, 0x00)) # 2
  84. self.xterm_colors.append((0xcd, 0xcd, 0x00)) # 3
  85. self.xterm_colors.append((0x00, 0x00, 0xee)) # 4
  86. self.xterm_colors.append((0xcd, 0x00, 0xcd)) # 5
  87. self.xterm_colors.append((0x00, 0xcd, 0xcd)) # 6
  88. self.xterm_colors.append((0xe5, 0xe5, 0xe5)) # 7
  89. self.xterm_colors.append((0x7f, 0x7f, 0x7f)) # 8
  90. self.xterm_colors.append((0xff, 0x00, 0x00)) # 9
  91. self.xterm_colors.append((0x00, 0xff, 0x00)) # 10
  92. self.xterm_colors.append((0xff, 0xff, 0x00)) # 11
  93. self.xterm_colors.append((0x5c, 0x5c, 0xff)) # 12
  94. self.xterm_colors.append((0xff, 0x00, 0xff)) # 13
  95. self.xterm_colors.append((0x00, 0xff, 0xff)) # 14
  96. self.xterm_colors.append((0xff, 0xff, 0xff)) # 15
  97. # colors 16..232: the 6x6x6 color cube
  98. valuerange = (0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff)
  99. for i in range(217):
  100. r = valuerange[(i / 36) % 6]
  101. g = valuerange[(i / 6) % 6]
  102. b = valuerange[i % 6]
  103. self.xterm_colors.append((r, g, b))
  104. # colors 233..253: grayscale
  105. for i in range(1, 22):
  106. v = 8 + i * 10
  107. self.xterm_colors.append((v, v, v))
  108. def _closest_color(self, r, g, b):
  109. distance = 257*257*3 # "infinity" (>distance from #000000 to #ffffff)
  110. match = 0
  111. for i in range(0, 254):
  112. values = self.xterm_colors[i]
  113. rd = r - values[0]
  114. gd = g - values[1]
  115. bd = b - values[2]
  116. d = rd*rd + gd*gd + bd*bd
  117. if d < distance:
  118. match = i
  119. distance = d
  120. return match
  121. def _color_index(self, color):
  122. index = self.best_match.get(color, None)
  123. if index is None:
  124. try:
  125. rgb = int(str(color), 16)
  126. except ValueError:
  127. rgb = 0
  128. r = (rgb >> 16) & 0xff
  129. g = (rgb >> 8) & 0xff
  130. b = rgb & 0xff
  131. index = self._closest_color(r, g, b)
  132. self.best_match[color] = index
  133. return index
  134. def _setup_styles(self):
  135. for ttype, ndef in self.style:
  136. escape = EscapeSequence()
  137. if ndef['color']:
  138. escape.fg = self._color_index(ndef['color'])
  139. if ndef['bgcolor']:
  140. escape.bg = self._color_index(ndef['bgcolor'])
  141. if self.usebold and ndef['bold']:
  142. escape.bold = True
  143. if self.useunderline and ndef['underline']:
  144. escape.underline = True
  145. self.style_string[str(ttype)] = (escape.color_string(),
  146. escape.reset_string())
  147. def format(self, tokensource, outfile):
  148. enc = self.encoding
  149. # hack: if the output is a terminal and has an encoding set,
  150. # use that to avoid unicode encode problems
  151. if not enc and hasattr(outfile, "encoding") and \
  152. hasattr(outfile, "isatty") and outfile.isatty():
  153. enc = outfile.encoding
  154. for ttype, value in tokensource:
  155. if enc:
  156. value = value.encode(enc)
  157. not_found = True
  158. while ttype and not_found:
  159. try:
  160. #outfile.write( "<" + str(ttype) + ">" )
  161. on, off = self.style_string[str(ttype)]
  162. # Like TerminalFormatter, add "reset colors" escape sequence
  163. # on newline.
  164. spl = value.split('\n')
  165. for line in spl[:-1]:
  166. if line:
  167. outfile.write(on + line + off)
  168. outfile.write('\n')
  169. if spl[-1]:
  170. outfile.write(on + spl[-1] + off)
  171. not_found = False
  172. #outfile.write( '#' + str(ttype) + '#' )
  173. except KeyError:
  174. #ottype = ttype
  175. ttype = ttype[:-1]
  176. #outfile.write( '!' + str(ottype) + '->' + str(ttype) + '!' )
  177. if not_found:
  178. outfile.write(value)