| 1 |
.. -*- mode: rst -*- |
| 2 |
|
| 3 |
======= |
| 4 |
Filters |
| 5 |
======= |
| 6 |
|
| 7 |
.. versionadded:: 0.7 |
| 8 |
|
| 9 |
Transforming a stream of tokens into another stream is called "filtering" and is |
| 10 |
done by filters. The most common example of filters transform each token by |
| 11 |
applying a simple rules such as highlighting the token if it is a TODO or |
| 12 |
another special word, or converting keywords to uppercase to enforce a style |
| 13 |
guide. More complex filters can transform the stream of tokens, such as removing |
| 14 |
the line indentation or merging tokens together. It should be noted that pygments |
| 15 |
filters are entirely unrelated to Python's `filter |
| 16 |
<https://docs.python.org/3/library/functions.html#filter>`_. |
| 17 |
|
| 18 |
An arbitrary number of filters can be applied to token streams coming from |
| 19 |
lexers to improve or annotate the output. To apply a filter, you can use the |
| 20 |
`add_filter()` method of a lexer: |
| 21 |
|
| 22 |
.. sourcecode:: pycon |
| 23 |
|
| 24 |
>>> from pygments.lexers import PythonLexer |
| 25 |
>>> l = PythonLexer() |
| 26 |
>>> # add a filter given by a string and options |
| 27 |
>>> l.add_filter('codetagify', case='lower') |
| 28 |
>>> l.filters |
| 29 |
[<pygments.filters.CodeTagFilter object at 0xb785decc>] |
| 30 |
>>> from pygments.filters import KeywordCaseFilter |
| 31 |
>>> # or give an instance |
| 32 |
>>> l.add_filter(KeywordCaseFilter(case='lower')) |
| 33 |
|
| 34 |
The `add_filter()` method takes keyword arguments which are forwarded to |
| 35 |
the constructor of the filter. |
| 36 |
|
| 37 |
To get a list of all registered filters by name, you can use the |
| 38 |
`get_all_filters()` function from the `pygments.filters` module that returns an |
| 39 |
iterable for all known filters. |
| 40 |
|
| 41 |
If you want to write your own filter, have a look at :doc:`Write your own filter |
| 42 |
<filterdevelopment>`. |
| 43 |
|
| 44 |
|
| 45 |
Builtin Filters |
| 46 |
=============== |
| 47 |
|
| 48 |
.. pygmentsdoc:: filters |