Is there a way to highlight function calls using Pygments (or another library)?

405 views Asked by At

I was quite disappointed to discover that functions calls were not highlighted using Pygments.

Pygments Syntax Highlighting

See it online (I tested it with all available styles)

Builtin functions are highlighted but not mine.

I looked at the tokens list but there is no reference to "function call" or "object attribute" for example.

I have considered extending the lexer by adding a regex rule like \w+\(.*?\). But I am afraid to multiply the errors because of edge cases I did not think of.

Do you know why this feature is not implemented directly inside Pygments?

1

There are 1 answers

0
Eric On

If you have a specific list of functions you want highlighted, you can add a custom highlighter like the builtin NumPyLexer:

from pygments.lexers.python import PythonLexer
from pygments.token import Keyword, Name, String

class MyFuncLexer(PythonLexer):
    name = 'MyFuncPython'
    aliases = ['myfuncpython']

    # override the mimetypes to not inherit them from python
    mimetypes = []
    filenames = []

    EXTRA_KEYWORDS = {
        'func'
    }

    def get_tokens_unprocessed(self, text):
        for index, token, value in \
                PythonLexer.get_tokens_unprocessed(self, text):
            if token is Name and value in self.EXTRA_KEYWORDS:
                yield index, Keyword.Pseudo, value
            else:
                yield index, token, value