filter.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # -*- coding: utf-8 -*-
  2. """
  3. pygments.filter
  4. ~~~~~~~~~~~~~~~
  5. Module that implements the default filter.
  6. :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
  7. :license: BSD, see LICENSE for details.
  8. """
  9. def apply_filters(stream, filters, lexer=None):
  10. """
  11. Use this method to apply an iterable of filters to
  12. a stream. If lexer is given it's forwarded to the
  13. filter, otherwise the filter receives `None`.
  14. """
  15. def _apply(filter_, stream):
  16. for token in filter_.filter(lexer, stream):
  17. yield token
  18. for filter_ in filters:
  19. stream = _apply(filter_, stream)
  20. return stream
  21. def simplefilter(f):
  22. """
  23. Decorator that converts a function into a filter::
  24. @simplefilter
  25. def lowercase(self, lexer, stream, options):
  26. for ttype, value in stream:
  27. yield ttype, value.lower()
  28. """
  29. return type(f.__name__, (FunctionFilter,), {
  30. '__module__': getattr(f, '__module__'),
  31. '__doc__': f.__doc__,
  32. 'function': f,
  33. })
  34. class Filter:
  35. """
  36. Default filter. Subclass this class or use the `simplefilter`
  37. decorator to create own filters.
  38. """
  39. def __init__(self, **options):
  40. self.options = options
  41. def filter(self, lexer, stream):
  42. raise NotImplementedError()
  43. class FunctionFilter(Filter):
  44. """
  45. Abstract class used by `simplefilter` to create simple
  46. function filters on the fly. The `simplefilter` decorator
  47. automatically creates subclasses of this class for
  48. functions passed to it.
  49. """
  50. function = None
  51. def __init__(self, **options):
  52. if not hasattr(self, 'function'):
  53. raise TypeError('%r used without bound function' %
  54. self.__class__.__name__)
  55. Filter.__init__(self, **options)
  56. def filter(self, lexer, stream):
  57. # pylint: disable=not-callable
  58. for ttype, value in self.function(lexer, stream, self.options):
  59. yield ttype, value