irc.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. """
  2. pygments.formatters.irc
  3. ~~~~~~~~~~~~~~~~~~~~~~~
  4. Formatter for IRC output
  5. :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
  6. :license: BSD, see LICENSE for details.
  7. """
  8. import sys
  9. from pygments.formatter import Formatter
  10. from pygments.token import Keyword, Name, Comment, String, Error, \
  11. Number, Operator, Generic, Token, Whitespace
  12. from pygments.util import get_choice_opt
  13. __all__ = ['IRCFormatter']
  14. #: Map token types to a tuple of color values for light and dark
  15. #: backgrounds.
  16. IRC_COLORS = {
  17. Token: ('', ''),
  18. Whitespace: ('gray', 'brightblack'),
  19. Comment: ('gray', 'brightblack'),
  20. Comment.Preproc: ('cyan', 'brightcyan'),
  21. Keyword: ('blue', 'brightblue'),
  22. Keyword.Type: ('cyan', 'brightcyan'),
  23. Operator.Word: ('magenta', 'brightcyan'),
  24. Name.Builtin: ('cyan', 'brightcyan'),
  25. Name.Function: ('green', 'brightgreen'),
  26. Name.Namespace: ('_cyan_', '_brightcyan_'),
  27. Name.Class: ('_green_', '_brightgreen_'),
  28. Name.Exception: ('cyan', 'brightcyan'),
  29. Name.Decorator: ('brightblack', 'gray'),
  30. Name.Variable: ('red', 'brightred'),
  31. Name.Constant: ('red', 'brightred'),
  32. Name.Attribute: ('cyan', 'brightcyan'),
  33. Name.Tag: ('brightblue', 'brightblue'),
  34. String: ('yellow', 'yellow'),
  35. Number: ('blue', 'brightblue'),
  36. Generic.Deleted: ('brightred', 'brightred'),
  37. Generic.Inserted: ('green', 'brightgreen'),
  38. Generic.Heading: ('**', '**'),
  39. Generic.Subheading: ('*magenta*', '*brightmagenta*'),
  40. Generic.Error: ('brightred', 'brightred'),
  41. Error: ('_brightred_', '_brightred_'),
  42. }
  43. IRC_COLOR_MAP = {
  44. 'white': 0,
  45. 'black': 1,
  46. 'blue': 2,
  47. 'brightgreen': 3,
  48. 'brightred': 4,
  49. 'yellow': 5,
  50. 'magenta': 6,
  51. 'orange': 7,
  52. 'green': 7, #compat w/ ansi
  53. 'brightyellow': 8,
  54. 'lightgreen': 9,
  55. 'brightcyan': 9, # compat w/ ansi
  56. 'cyan': 10,
  57. 'lightblue': 11,
  58. 'red': 11, # compat w/ ansi
  59. 'brightblue': 12,
  60. 'brightmagenta': 13,
  61. 'brightblack': 14,
  62. 'gray': 15,
  63. }
  64. def ircformat(color, text):
  65. if len(color) < 1:
  66. return text
  67. add = sub = ''
  68. if '_' in color: # italic
  69. add += '\x1D'
  70. sub = '\x1D' + sub
  71. color = color.strip('_')
  72. if '*' in color: # bold
  73. add += '\x02'
  74. sub = '\x02' + sub
  75. color = color.strip('*')
  76. # underline (\x1F) not supported
  77. # backgrounds (\x03FF,BB) not supported
  78. if len(color) > 0: # actual color - may have issues with ircformat("red", "blah")+"10" type stuff
  79. add += '\x03' + str(IRC_COLOR_MAP[color]).zfill(2)
  80. sub = '\x03' + sub
  81. return add + text + sub
  82. return '<'+add+'>'+text+'</'+sub+'>'
  83. class IRCFormatter(Formatter):
  84. r"""
  85. Format tokens with IRC color sequences
  86. The `get_style_defs()` method doesn't do anything special since there is
  87. no support for common styles.
  88. Options accepted:
  89. `bg`
  90. Set to ``"light"`` or ``"dark"`` depending on the terminal's background
  91. (default: ``"light"``).
  92. `colorscheme`
  93. A dictionary mapping token types to (lightbg, darkbg) color names or
  94. ``None`` (default: ``None`` = use builtin colorscheme).
  95. `linenos`
  96. Set to ``True`` to have line numbers in the output as well
  97. (default: ``False`` = no line numbers).
  98. """
  99. name = 'IRC'
  100. aliases = ['irc', 'IRC']
  101. filenames = []
  102. def __init__(self, **options):
  103. Formatter.__init__(self, **options)
  104. self.darkbg = get_choice_opt(options, 'bg',
  105. ['light', 'dark'], 'light') == 'dark'
  106. self.colorscheme = options.get('colorscheme', None) or IRC_COLORS
  107. self.linenos = options.get('linenos', False)
  108. self._lineno = 0
  109. def _write_lineno(self, outfile):
  110. self._lineno += 1
  111. outfile.write("\n%04d: " % self._lineno)
  112. def _format_unencoded_with_lineno(self, tokensource, outfile):
  113. self._write_lineno(outfile)
  114. for ttype, value in tokensource:
  115. if value.endswith("\n"):
  116. self._write_lineno(outfile)
  117. value = value[:-1]
  118. color = self.colorscheme.get(ttype)
  119. while color is None:
  120. ttype = ttype[:-1]
  121. color = self.colorscheme.get(ttype)
  122. if color:
  123. color = color[self.darkbg]
  124. spl = value.split('\n')
  125. for line in spl[:-1]:
  126. self._write_lineno(outfile)
  127. if line:
  128. outfile.write(ircformat(color, line[:-1]))
  129. if spl[-1]:
  130. outfile.write(ircformat(color, spl[-1]))
  131. else:
  132. outfile.write(value)
  133. outfile.write("\n")
  134. def format_unencoded(self, tokensource, outfile):
  135. if self.linenos:
  136. self._format_unencoded_with_lineno(tokensource, outfile)
  137. return
  138. for ttype, value in tokensource:
  139. color = self.colorscheme.get(ttype)
  140. while color is None:
  141. ttype = ttype[:-1]
  142. color = self.colorscheme.get(ttype)
  143. if color:
  144. color = color[self.darkbg]
  145. spl = value.split('\n')
  146. for line in spl[:-1]:
  147. if line:
  148. outfile.write(ircformat(color, line))
  149. outfile.write('\n')
  150. if spl[-1]:
  151. outfile.write(ircformat(color, spl[-1]))
  152. else:
  153. outfile.write(value)