Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1# -*- coding: utf-8 -*- 

2""" 

3 pygments.filter 

4 ~~~~~~~~~~~~~~~ 

5 

6 Module that implements the default filter. 

7 

8 :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS. 

9 :license: BSD, see LICENSE for details. 

10""" 

11 

12 

13def apply_filters(stream, filters, lexer=None): 

14 """ 

15 Use this method to apply an iterable of filters to 

16 a stream. If lexer is given it's forwarded to the 

17 filter, otherwise the filter receives `None`. 

18 """ 

19 def _apply(filter_, stream): 

20 yield from filter_.filter(lexer, stream) 

21 for filter_ in filters: 

22 stream = _apply(filter_, stream) 

23 return stream 

24 

25 

26def simplefilter(f): 

27 """ 

28 Decorator that converts a function into a filter:: 

29 

30 @simplefilter 

31 def lowercase(self, lexer, stream, options): 

32 for ttype, value in stream: 

33 yield ttype, value.lower() 

34 """ 

35 return type(f.__name__, (FunctionFilter,), { 

36 '__module__': getattr(f, '__module__'), 

37 '__doc__': f.__doc__, 

38 'function': f, 

39 }) 

40 

41 

42class Filter: 

43 """ 

44 Default filter. Subclass this class or use the `simplefilter` 

45 decorator to create own filters. 

46 """ 

47 

48 def __init__(self, **options): 

49 self.options = options 

50 

51 def filter(self, lexer, stream): 

52 raise NotImplementedError() 

53 

54 

55class FunctionFilter(Filter): 

56 """ 

57 Abstract class used by `simplefilter` to create simple 

58 function filters on the fly. The `simplefilter` decorator 

59 automatically creates subclasses of this class for 

60 functions passed to it. 

61 """ 

62 function = None 

63 

64 def __init__(self, **options): 

65 if not hasattr(self, 'function'): 

66 raise TypeError('%r used without bound function' % 

67 self.__class__.__name__) 

68 Filter.__init__(self, **options) 

69 

70 def filter(self, lexer, stream): 

71 # pylint: disable=not-callable 

72 yield from self.function(lexer, stream, self.options)