Back to index

moin  1.9.0~rc2
filter.py
Go to the documentation of this file.
00001 # -*- coding: utf-8 -*-
00002 """
00003     pygments.filter
00004     ~~~~~~~~~~~~~~~
00005 
00006     Module that implements the default filter.
00007 
00008     :copyright: Copyright 2006-2009 by the Pygments team, see AUTHORS.
00009     :license: BSD, see LICENSE for details.
00010 """
00011 
00012 
00013 def apply_filters(stream, filters, lexer=None):
00014     """
00015     Use this method to apply an iterable of filters to
00016     a stream. If lexer is given it's forwarded to the
00017     filter, otherwise the filter receives `None`.
00018     """
00019     def _apply(filter_, stream):
00020         for token in filter_.filter(lexer, stream):
00021             yield token
00022     for filter_ in filters:
00023         stream = _apply(filter_, stream)
00024     return stream
00025 
00026 
00027 def simplefilter(f):
00028     """
00029     Decorator that converts a function into a filter::
00030 
00031         @simplefilter
00032         def lowercase(lexer, stream, options):
00033             for ttype, value in stream:
00034                 yield ttype, value.lower()
00035     """
00036     return type(f.__name__, (FunctionFilter,), {
00037                 'function':     f,
00038                 '__module__':   getattr(f, '__module__'),
00039                 '__doc__':      f.__doc__
00040             })
00041 
00042 
00043 class Filter(object):
00044     """
00045     Default filter. Subclass this class or use the `simplefilter`
00046     decorator to create own filters.
00047     """
00048 
00049     def __init__(self, **options):
00050         self.options = options
00051 
00052     def filter(self, lexer, stream):
00053         raise NotImplementedError()
00054 
00055 
00056 class FunctionFilter(Filter):
00057     """
00058     Abstract class used by `simplefilter` to create simple
00059     function filters on the fly. The `simplefilter` decorator
00060     automatically creates subclasses of this class for
00061     functions passed to it.
00062     """
00063     function = None
00064 
00065     def __init__(self, **options):
00066         if not hasattr(self, 'function'):
00067             raise TypeError('%r used without bound function' %
00068                             self.__class__.__name__)
00069         Filter.__init__(self, **options)
00070 
00071     def filter(self, lexer, stream):
00072         # pylint: disable-msg=E1102
00073         for ttype, value in self.function(lexer, stream, self.options):
00074             yield ttype, value