terminal.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. """
  2. pygments.formatters.terminal
  3. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. Formatter for terminal output with ANSI sequences.
  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.console import ansiformat
  13. from pygments.util import get_choice_opt
  14. __all__ = ['TerminalFormatter']
  15. #: Map token types to a tuple of color values for light and dark
  16. #: backgrounds.
  17. TERMINAL_COLORS = {
  18. Token: ('', ''),
  19. Whitespace: ('gray', 'brightblack'),
  20. Comment: ('gray', 'brightblack'),
  21. Comment.Preproc: ('cyan', 'brightcyan'),
  22. Keyword: ('blue', 'brightblue'),
  23. Keyword.Type: ('cyan', 'brightcyan'),
  24. Operator.Word: ('magenta', 'brightmagenta'),
  25. Name.Builtin: ('cyan', 'brightcyan'),
  26. Name.Function: ('green', 'brightgreen'),
  27. Name.Namespace: ('_cyan_', '_brightcyan_'),
  28. Name.Class: ('_green_', '_brightgreen_'),
  29. Name.Exception: ('cyan', 'brightcyan'),
  30. Name.Decorator: ('brightblack', 'gray'),
  31. Name.Variable: ('red', 'brightred'),
  32. Name.Constant: ('red', 'brightred'),
  33. Name.Attribute: ('cyan', 'brightcyan'),
  34. Name.Tag: ('brightblue', 'brightblue'),
  35. String: ('yellow', 'yellow'),
  36. Number: ('blue', 'brightblue'),
  37. Generic.Deleted: ('brightred', 'brightred'),
  38. Generic.Inserted: ('green', 'brightgreen'),
  39. Generic.Heading: ('**', '**'),
  40. Generic.Subheading: ('*magenta*', '*brightmagenta*'),
  41. Generic.Prompt: ('**', '**'),
  42. Generic.Error: ('brightred', 'brightred'),
  43. Error: ('_brightred_', '_brightred_'),
  44. }
  45. class TerminalFormatter(Formatter):
  46. r"""
  47. Format tokens with ANSI color sequences, for output in a text console.
  48. Color sequences are terminated at newlines, so that paging the output
  49. works correctly.
  50. The `get_style_defs()` method doesn't do anything special since there is
  51. no support for common styles.
  52. Options accepted:
  53. `bg`
  54. Set to ``"light"`` or ``"dark"`` depending on the terminal's background
  55. (default: ``"light"``).
  56. `colorscheme`
  57. A dictionary mapping token types to (lightbg, darkbg) color names or
  58. ``None`` (default: ``None`` = use builtin colorscheme).
  59. `linenos`
  60. Set to ``True`` to have line numbers on the terminal output as well
  61. (default: ``False`` = no line numbers).
  62. """
  63. name = 'Terminal'
  64. aliases = ['terminal', 'console']
  65. filenames = []
  66. def __init__(self, **options):
  67. Formatter.__init__(self, **options)
  68. self.darkbg = get_choice_opt(options, 'bg',
  69. ['light', 'dark'], 'light') == 'dark'
  70. self.colorscheme = options.get('colorscheme', None) or TERMINAL_COLORS
  71. self.linenos = options.get('linenos', False)
  72. self._lineno = 0
  73. def format(self, tokensource, outfile):
  74. return Formatter.format(self, tokensource, outfile)
  75. def _write_lineno(self, outfile):
  76. self._lineno += 1
  77. outfile.write("%s%04d: " % (self._lineno != 1 and '\n' or '', self._lineno))
  78. def _get_color(self, ttype):
  79. # self.colorscheme is a dict containing usually generic types, so we
  80. # have to walk the tree of dots. The base Token type must be a key,
  81. # even if it's empty string, as in the default above.
  82. colors = self.colorscheme.get(ttype)
  83. while colors is None:
  84. ttype = ttype.parent
  85. colors = self.colorscheme.get(ttype)
  86. return colors[self.darkbg]
  87. def format_unencoded(self, tokensource, outfile):
  88. if self.linenos:
  89. self._write_lineno(outfile)
  90. for ttype, value in tokensource:
  91. color = self._get_color(ttype)
  92. for line in value.splitlines(True):
  93. if color:
  94. outfile.write(ansiformat(color, line.rstrip('\n')))
  95. else:
  96. outfile.write(line.rstrip('\n'))
  97. if line.endswith('\n'):
  98. if self.linenos:
  99. self._write_lineno(outfile)
  100. else:
  101. outfile.write('\n')
  102. if self.linenos:
  103. outfile.write("\n")