1. Blue Goji
  2. Untitled project
  3. pygments-main


pygments-main / pygments / formatters / terminal.py

The branch 'trunk' does not exist.
# -*- coding: utf-8 -*-

    Formatter for terminal output with ANSI sequences.

    :copyright: 2006 by Georg Brandl.
    :license: BSD, see LICENSE for more details.

from pygments.formatter import Formatter
from pygments.token import Keyword, Name, Comment, String, Error, \
     Number, Operator, Generic, Token
from pygments.console import ansiformat

__all__ = ['TerminalFormatter']

#: Map token types to a tuple of color values for light and dark
#: backgrounds.
    Token:              ('',            ''),

    Comment:            ('lightgray',   'darkgray'),
    Keyword:            ('darkblue',    'blue'),
    Keyword.Type:       ('teal',        'turquoise'),
    Operator.Word:      ('purple',      'fuchsia'),
    Name.Builtin:       ('teal',        'turquoise'),
    Name.Function:      ('darkgreen',   'green'),
    Name.Namespace:     ('_teal_',      '_turquoise_'),
    Name.Class:         ('_darkgreen_', '_green_'),
    Name.Exception:     ('teal',        'turquoise'),
    Name.Decorator:     ('darkgray',    'lightgray'),
    Name.Variable:      ('darkred',     'red'),
    Name.Constant:      ('darkred',     'red'),
    Name.Attribute:     ('teal',        'turquoise'),
    Name.Tag:           ('blue',        'blue'),
    String:             ('brown',       'brown'),
    Number:             ('darkblue',    'blue'),

    Generic.Deleted:    ('red',        'red'),
    Generic.Inserted:   ('darkgreen',  'green'),
    Generic.Heading:    ('**',         '**'),
    Generic.Subheading: ('*purple*',   '*fuchsia*'),
    Generic.Error:      ('red',        'red'),

    Error:              ('_red_',      '_red_'),

class TerminalFormatter(Formatter):
    Output plain text with coloring ANSI sequences.

    def __init__(self, **options):
        Accepted options:

            Set to ``'light'`` or ``'dark'`` depending on the
            terminal's background.

            ``None`` or a dictionary mapping token types to
            ``(lightbg, darkbg)`` color names.
        Formatter.__init__(self, **options)
        self.darkbg = options.get('bg', 'light') == 'dark'
        self.colorscheme = options.get('colorscheme', None) or TERMINAL_COLORS

    def format(self, tokensource, outfile):
        enc = self.encoding
        for ttype, value in tokensource:
            if enc:
                value = value.encode(enc)
            color = self.colorscheme.get(ttype)
            while color is None:
                ttype = ttype[:-1]
                color = self.colorscheme.get(ttype)
            if color:
                color = color[self.darkbg]
                spl = value.split('\n')
                for line in spl[:-1]:
                    if line:
                        outfile.write(ansiformat(color, line))
                if spl[-1]:
                    outfile.write(ansiformat(color, spl[-1]))