Example #1
0
 def initialize(self, debug):
   logger = logging.getLogger('cast')
   logger.setLevel(logging.DEBUG)
   stdoutLogger = logging.StreamHandler()
   stdoutLogger.setLevel(logging.DEBUG)
   colormap = XTermColorMap()
   debug = '[%10s]' % (colormap.colorize('debug', 0x00ff00))
   formatter = logging.Formatter('%s%(levelname)-10s%s %(message)s')
   stdoutLogger.setFormatter(formatter)
   if debug:
     logger.addHandler(stdoutLogger)
   return logger
Example #2
0
def Cli():
  parser = argparse.ArgumentParser(
              description = 'xtermcolor: 256 terminal color library')

  parser.add_argument('action',
              choices = ['convert', 'list'],
              help = 'Actions')

  parser.add_argument('--color',
              help = 'Color to convert')

  parser.add_argument('--compat',
              choices=['xterm', 'vt100'],
              default='xterm',
              help = 'Compatibility mode.  Defaults to xterm.')

  cli = parser.parse_args()

  if cli.compat.lower() not in ['xterm', 'vt100']:
    sys.stderr.write('Error: --compat must be xterm or vt100\n')
    sys.exit(-1)
  
  if cli.compat.lower() == 'xterm':
    colorMap = XTermColorMap()
  if cli.compat.lower() == 'vt100':
    colorMap = VT100ColorMap()

  if cli.action == 'list':
    for xterm, hexcolor in colorMap.getColors().items():
      string = "\033[38;5;{xterm:d}mansi={xterm:d}; rgb=#{hexcolor:06x}; printf={cprintf:s}\033[0m"
      print(string.format(xterm=xterm, hexcolor=hexcolor, cprintf=cPrintfString(xterm)));

  if cli.action == 'convert':
    if not cli.color:
      sys.stderr.write('Error: must specify --color\n')
      sys.exit(-1)
    if cli.color[0] == '#':
      cli.color = '0x' + cli.color[1:]
    cli.color = int(cli.color, 16)
    
    colorizedMsg = colorMap.colorize('The quick brown fox jumped over the lazy dog.', cli.color)
    (ansi, rgb) = colorMap.convert(cli.color)
    print("#{start:06x} is closest to #{closest:06x} which is ANSI code {ansi:d}\n".format( \
          start=cli.color, closest=rgb, ansi=ansi))
    print("Example: " + colorizedMsg)
    print("printf() string: " + cPrintfString(ansi))
Example #3
0
  def __init__(self, tokenList, parsetree=None, grammar=None, ast=None, theme=None, highlight=False):
    self.__dict__.update(locals())
    self.string = ''
    self.lineno = 1
    self.colno = 1
    self.ancestors = dict([(t, set()) for t in self.tokenList])
    self.parents = dict([(t, set()) for t in self.tokenList])
    self.getTokenAncestors(ast)
    self.termcolor = XTermColorMap()
    c = lambda x: c_Parser.terminals[x]
    self.insertSpaceAfter = {
      c('else')
    }

    # bah, cruft
    self.keywords = []
Example #4
0
def colorize(string, rgb=None, ansi=None, bg=None, ansi_bg=None, fd=1):
    '''Returns the colored string to print on the terminal.
    
    This function detects the terminal type and if it is supported and the
    output is not going to a pipe or a file, then it will return the colored
    string, otherwise it will return the string without modifications.
    
    string = the string to print. Only accepts strings, unicode strings must
             be encoded in advance.
    rgb    = Rgb color for the text; for example 0xFF0000 is red.
    ansi   = Ansi for the text
    bg     = Rgb color for the background
    ansi_bg= Ansi color for the background
    fd     = The file descriptor that will be used by print, by default is the
             stdout
    '''

    #Reinitializes if fd used is different
    if colorize.fd != fd:
        colorize.init = False
        colorize.fd = fd

    #Checks if it is on a terminal, and if the terminal is recognized
    if not colorize.init:
        colorize.init = True
        colorize.is_term = isatty(fd)
        if 'TERM' in environ:
            if environ['TERM'].startswith('xterm'):
                colorize.cmap = XTermColorMap()
            elif environ['TERM'] == 'vt100':
                colorize.cmap = VT100ColorMap()
            else:
                colorize.is_term = False
        else:
            colorize.is_term = False

    if colorize.is_term:
        string = colorize.cmap.colorize(string, rgb, ansi, bg, ansi_bg)

    return string
Example #5
0
class SourceCodeWriter:
  def __init__(self, tokenList, parsetree=None, grammar=None, ast=None, theme=None, highlight=False):
    self.__dict__.update(locals())
    self.string = ''
    self.lineno = 1
    self.colno = 1
    self.ancestors = dict([(t, set()) for t in self.tokenList])
    self.parents = dict([(t, set()) for t in self.tokenList])
    self.getTokenAncestors(ast)
    self.termcolor = XTermColorMap()
    c = lambda x: c_Parser.terminals[x]
    self.insertSpaceAfter = {
      c('else')
    }

    # bah, cruft
    self.keywords = []

  def getTokenAncestors(self, ast):
    self.stack = []
    self._getTokenAncestors(ast)

  def _getTokenAncestors(self, ast):
    if not ast:
      return
    self.stack.append(ast.name)
    for (attr, obj) in ast.attributes.items():
      if isinstance(obj, cToken):
        self.ancestors[obj] = self.ancestors[obj].union(set(self.stack))
        self.parents[obj] = (self.stack[-1], attr)
      elif isinstance(obj, Ast):
        self._getTokenAncestors(obj)
      elif isinstance(obj, list):
        for x in obj:
          if isinstance(x, cToken):
            self.ancestors[x] = self.ancestors[x].union(set(self.stack))
            self.parents[x] = (self.stack[-1], attr)
          else:
            self._getTokenAncestors(x)
    self.stack.pop()

  def add(self, token):
    if token.lineno > self.lineno:
      self.string += ''.join('\n' for i in range(token.lineno - self.lineno))
      self.lineno = token.lineno
      self.colno = 1
    if token.colno > self.colno:
      self.string += ''.join(' ' for i in range(token.colno - self.colno))
      self.colno = token.colno

    self.string += self.doHighlight(token)

    if token.fromPreprocessor or token.id in self.insertSpaceAfter:
      self.string += ' '
    self.colno += len(token.source_string)

  def doHighlight(self, token):
    if not self.highlight:
      return token.source_string

    if token in self.parents and len(self.parents[token]):
      (parent, attr) = self.parents[token]
      if attr == 'declaration_specifiers':
        return self.termcolor.colorize(token.source_string, 0x0087ff)
      if parent == 'FuncCall' and attr == 'name':
        return self.termcolor.colorize(token.source_string, 0x8700ff)
      if parent == 'FunctionSignature' and attr == 'declarator':
        return self.termcolor.colorize(token.source_string, 0xff8700)
    if self.grammar:
      if not len(self.keywords):
        for rule in self.grammar.getRules():
          terminal = rule.isTokenAlias()
          if terminal and rule.nonterminal.string == 'keyword':
            self.keywords.append(terminal.string)
      if token.terminal_str in self.keywords:
        return self.termcolor.colorize(token.source_string, 0xffff00)
    if token.terminal_str == 'string_literal':
      return self.termcolor.colorize(token.source_string, 0xff0000)
    if token.terminal_str == 'identifier':
      return self.termcolor.colorize(token.source_string, 0x00ff00)

    return token.source_string

  def __str__(self):
    if not len(self.string):
      for token in self.tokenList:
        self.add(token)
    return self.string