Debian Codegraph @

doc/docs/filterdevelopment.rst

raw
1 .. -*- mode: rst -*-
2
3 =====================
4 Write your own filter
5 =====================
6
7 .. versionadded:: 0.7
8
9 Writing own filters is very easy. All you have to do is to subclass
10 the `Filter` class and override the `filter` method. Additionally a
11 filter is instantiated with some keyword arguments you can use to
12 adjust the behavior of your filter.
13
14
15 Subclassing Filters
16 ===================
17
18 As an example, we write a filter that converts all `Name.Function` tokens
19 to normal `Name` tokens to make the output less colorful.
20
21 .. sourcecode:: python
22
23 from pygments.util import get_bool_opt
24 from pygments.token import Name
25 from pygments.filter import Filter
26
27 class UncolorFilter(Filter):
28
29 def __init__(self, **options):
30 Filter.__init__(self, **options)
31 self.class_too = get_bool_opt(options, 'classtoo')
32
33 def filter(self, lexer, stream):
34 for ttype, value in stream:
35 if ttype is Name.Function or (self.class_too and
36 ttype is Name.Class):
37 ttype = Name
38 yield ttype, value
39
40 Some notes on the `lexer` argument: that can be quite confusing since it doesn't
41 need to be a lexer instance. If a filter was added by using the `add_filter()`
42 function of lexers, that lexer is registered for the filter. In that case
43 `lexer` will refer to the lexer that has registered the filter. It *can* be used
44 to access options passed to a lexer. Because it could be `None` you always have
45 to check for that case if you access it.
46
47
48 Using a decorator
49 =================
50
51 You can also use the `simplefilter` decorator from the `pygments.filter` module:
52
53 .. sourcecode:: python
54
55 from pygments.util import get_bool_opt
56 from pygments.token import Name
57 from pygments.filter import simplefilter
58
59
60 @simplefilter
61 def uncolor(self, lexer, stream, options):
62 class_too = get_bool_opt(options, 'classtoo')
63 for ttype, value in stream:
64 if ttype is Name.Function or (class_too and
65 ttype is Name.Class):
66 ttype = Name
67 yield ttype, value
68
69
70 You can instantiate this filter by calling `uncolor(classtoo=True)`, the same
71 way that you would have instantiated the previous filter by calling
72 `UncolorFilter(classtoo=True)`. Indeed, The decorator automatically ensures that
73 `uncolor` is a class which subclasses an internal filter class. The class
74 `uncolo` uses the decorated function as a method for filtering. (That's why
75 there is a `self` argument that you probably won't end up using in the method.)