[Urwid] palette container

Alain Leufroy alain.leufroy at logilab.fr
Tue Aug 16 07:11:07 EDT 2011


Hi,

I'd like to use pygments to colorize source file data displayed in a Text
widget.

To do so, I set a palette with names from pygments tokens. Here is a simple
example::

--- 8< ---- Begin (test.py) ---- 8< ----
#! /usr/bin/env python

import urwid
from pygments import lex, lexers, token

class Foo(object):
     '''Just to get a class'''

     def __str__(self):
         '''return this python source code as a string'''
         fid = open(__file__)
         python_code = fid.read()
         fid.close()
         return python_code

def highlight_code(text):
     """return formated text using pygments"""
     return list(lex(text, lexers.PythonLexer()))

PALETTE = [(token.Token.Text, 'default', 'default'),
            (token.Token.Name, 'dark blue', 'default'),
            (token.Token.Name.Function, 'light blue', 'default'),
            (token.Token.Comment, 'dark gray', 'default'),
            (token.Token.Literal.String, 'yellow', 'default'),
            ]

text = highlight_code(str(Foo()))
widget = urwid.Filler(urwid.Text(text))
screen = urwid.raw_display.Screen()
mainloop = urwid.MainLoop(widget, PALETTE, screen)
mainloop.run()
--- 8< ---- End (test.py) ---- 8< ----

Running ``python test.py`` displays a highlighted source code. But it is not
exactly what as I expect.

For example, *Foo* is not highlighted because pygments sets the "style" to
*token.Token.Name.Class*. But I'd like that *Foo* is in "dark blue" because
*token.Token.Name.Class* is a "sub-style" of *token.Token.Name* (instead of
defining all "sub-style of "token.Token.Name" to the same style).



More information about the Urwid mailing list