New in version 0.7.
You can filter token streams coming from lexers to improve or annotate the output. For example, you can highlight special words in comments, convert keywords to upper or lowercase to enforce a style guide etc.
To apply a filter, you can use the add_filter() method of a lexer:
>>> from pygments.lexers import PythonLexer
>>> l = PythonLexer()
>>> # add a filter given by a string and options
>>> l.add_filter('codetagify', case='lower')
>>> l.filters
[<pygments.filters.CodeTagFilter object at 0xb785decc>]
>>> from pygments.filters import KeywordCaseFilter
>>> # or give an instance
>>> l.add_filter(KeywordCaseFilter(case='lower'))
The add_filter() method takes keyword arguments which are forwarded to the constructor of the filter.
To get a list of all registered filters by name, you can use the get_all_filters() function from the pygments.filters module that returns an iterable for all known filters.
If you want to write your own filter, have a look at Write your own filter.
Name: | raiseonerror |
---|
Raise an exception when the lexer generates an error token.
Options accepted:
New in version 0.8.
Name: | whitespace |
---|
Convert tabs, newlines and/or spaces to visible characters.
Options accepted:
New in version 0.8.
Name: | tokenmerge |
---|
Merges consecutive tokens with the same token type in the output stream of a lexer.
New in version 1.2.
Name: | gobble |
---|
Gobbles source code lines (eats initial characters).
This filter drops the first n characters off every line of code. This may be useful when the source code fed to the lexer is indented by a fixed amount of space that isn’t desired in the output.
Options accepted:
New in version 1.2.
Name: | highlight |
---|
Highlight a normal Name (and Name.*) token with a different token type.
Example:
filter = NameHighlightFilter(
names=['foo', 'bar', 'baz'],
tokentype=Name.Function,
)
This would highlight the names “foo”, “bar” and “baz” as functions. Name.Function is the default token type.
Options accepted:
Name: | codetagify |
---|
Highlight special code tags in comments and docstrings.
Options accepted:
Name: | keywordcase |
---|
Convert keywords to lowercase or uppercase or capitalize them, which means first letter uppercase, rest lowercase.
This can be useful e.g. if you highlight Pascal code and want to adapt the code to your styleguide.
Options accepted: