Back to index

moin  1.9.0~rc2
terminal.py
Go to the documentation of this file.
00001 # -*- coding: utf-8 -*-
00002 """
00003     pygments.formatters.terminal
00004     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
00005 
00006     Formatter for terminal output with ANSI sequences.
00007 
00008     :copyright: Copyright 2006-2009 by the Pygments team, see AUTHORS.
00009     :license: BSD, see LICENSE for details.
00010 """
00011 
00012 from pygments.formatter import Formatter
00013 from pygments.token import Keyword, Name, Comment, String, Error, \
00014      Number, Operator, Generic, Token, Whitespace
00015 from pygments.console import ansiformat
00016 from pygments.util import get_choice_opt
00017 
00018 
00019 __all__ = ['TerminalFormatter']
00020 
00021 
00022 #: Map token types to a tuple of color values for light and dark
00023 #: backgrounds.
00024 TERMINAL_COLORS = {
00025     Token:              ('',            ''),
00026 
00027     Whitespace:         ('lightgray',   'darkgray'),
00028     Comment:            ('lightgray',   'darkgray'),
00029     Comment.Preproc:    ('teal',        'turquoise'),
00030     Keyword:            ('darkblue',    'blue'),
00031     Keyword.Type:       ('teal',        'turquoise'),
00032     Operator.Word:      ('purple',      'fuchsia'),
00033     Name.Builtin:       ('teal',        'turquoise'),
00034     Name.Function:      ('darkgreen',   'green'),
00035     Name.Namespace:     ('_teal_',      '_turquoise_'),
00036     Name.Class:         ('_darkgreen_', '_green_'),
00037     Name.Exception:     ('teal',        'turquoise'),
00038     Name.Decorator:     ('darkgray',    'lightgray'),
00039     Name.Variable:      ('darkred',     'red'),
00040     Name.Constant:      ('darkred',     'red'),
00041     Name.Attribute:     ('teal',        'turquoise'),
00042     Name.Tag:           ('blue',        'blue'),
00043     String:             ('brown',       'brown'),
00044     Number:             ('darkblue',    'blue'),
00045 
00046     Generic.Deleted:    ('red',        'red'),
00047     Generic.Inserted:   ('darkgreen',  'green'),
00048     Generic.Heading:    ('**',         '**'),
00049     Generic.Subheading: ('*purple*',   '*fuchsia*'),
00050     Generic.Error:      ('red',        'red'),
00051 
00052     Error:              ('_red_',      '_red_'),
00053 }
00054 
00055 
00056 class TerminalFormatter(Formatter):
00057     r"""
00058     Format tokens with ANSI color sequences, for output in a text console.
00059     Color sequences are terminated at newlines, so that paging the output
00060     works correctly.
00061 
00062     The `get_style_defs()` method doesn't do anything special since there is
00063     no support for common styles.
00064 
00065     Options accepted:
00066 
00067     `bg`
00068         Set to ``"light"`` or ``"dark"`` depending on the terminal's background
00069         (default: ``"light"``).
00070 
00071     `colorscheme`
00072         A dictionary mapping token types to (lightbg, darkbg) color names or
00073         ``None`` (default: ``None`` = use builtin colorscheme).
00074     """
00075     name = 'Terminal'
00076     aliases = ['terminal', 'console']
00077     filenames = []
00078 
00079     def __init__(self, **options):
00080         Formatter.__init__(self, **options)
00081         self.darkbg = get_choice_opt(options, 'bg',
00082                                      ['light', 'dark'], 'light') == 'dark'
00083         self.colorscheme = options.get('colorscheme', None) or TERMINAL_COLORS
00084 
00085     def format(self, tokensource, outfile):
00086         # hack: if the output is a terminal and has an encoding set,
00087         # use that to avoid unicode encode problems
00088         if not self.encoding and hasattr(outfile, "encoding") and \
00089            hasattr(outfile, "isatty") and outfile.isatty():
00090             self.encoding = outfile.encoding
00091         return Formatter.format(self, tokensource, outfile)
00092 
00093     def format_unencoded(self, tokensource, outfile):
00094         for ttype, value in tokensource:
00095             color = self.colorscheme.get(ttype)
00096             while color is None:
00097                 ttype = ttype[:-1]
00098                 color = self.colorscheme.get(ttype)
00099             if color:
00100                 color = color[self.darkbg]
00101                 spl = value.split('\n')
00102                 for line in spl[:-1]:
00103                     if line:
00104                         outfile.write(ansiformat(color, line))
00105                     outfile.write('\n')
00106                 if spl[-1]:
00107                     outfile.write(ansiformat(color, spl[-1]))
00108             else:
00109                 outfile.write(value)