Changeset 1436


Ignore:
Timestamp:
Oct 22, 2006, 10:18:02 PM (17 years ago)
Author:
Matt Good
Message:

TracPygmentsPlugin:

use the Trac CSS classes for code coloring

File:
1 edited

Legend:

Unmodified
Added
Removed
  • tracpygmentsplugin/0.11/tracpygments/__init__.py

    r1416 r1436  
    108108    import pygments
    109109    lexer = pygments.get_lexer_by_name(lang)
    110     formatter = pygments.get_formatter_by_name('html', noclasses=True,
    111                     cssclass = not annotate and 'code' or '')
     110    formatter = TracHtmlFormatter(cssclass = not annotate and 'code' or '')
    112111    html = pygments.highlight(content, lexer, formatter).rstrip('\n')
    113112    if annotate:
     
    138137    def render_macro(self, req, name, content):
    139138        return _format(name, content)
     139
     140try:
     141    import pygments
     142except ImportError:
     143    pass
     144else:
     145    from pygments.formatters.html import HtmlFormatter
     146    from pygments.token import *
     147
     148    def _issubtoken(token, base):
     149        while token is not None:
     150            if token == base:
     151                return True
     152            token = token.parent
     153        return False
     154
     155    class TracHtmlFormatter(HtmlFormatter):
     156        token_classes = [
     157            (Comment, 'code-comment'),
     158            (Name.Function, 'code-func'),
     159            (Name.Variable, 'code-var'),
     160            (Name, 'code-lang'),
     161            (String, 'code-string'),
     162            (Keyword.Type, 'code-type'),
     163            (Keyword, 'code-keyword'),
     164            (Token, None),
     165        ]
     166
     167        def _get_css_class(self, ttype):
     168            try:
     169                return self._class_cache[ttype]
     170            except KeyError:
     171                pass
     172            for token, css_class in self.token_classes:
     173                if _issubtoken(ttype, token):
     174                    break
     175            else:
     176                css_class = None
     177            if css_class is not None:
     178                css_class = self.classprefix + css_class
     179            self._class_cache[ttype] = css_class
     180            return css_class
Note: See TracChangeset for help on using the changeset viewer.