Search code examples
pythonvimvim-syntax-highlighting

In Vimscript, is it possible to access information known by the syntax highlighter?


For example, if I am writing a Vimscript function to operate on Python syntax, it might be useful to know whether a line is regular code, a comment, or enclosed in triple-quotes. I assume that the syntax highligher has already figured out such things. Can I easily access that information in my own Vim functions, or do I have to roll my own parsing logic?

def eight_the_hard_way():
    '''
    Blah blah.
    '''
    # Blort!
    x = 4 + 4
    return x

I've searched a fair bit for this information, but haven't found anything directly on this topic so far.


Solution

  • Yes, with the synID() function, you can obtain the syntax ID at a particular cursor position.

    There are two complications:

    1. You usually want to compare against a particular highlight group (e.g. Comment)
    2. Because of syntax nesting, there can actually be an entire stack of syntaxes at a position.

    The :help synID() has additional hints and pointers how to solve these. My ingo-library plugin provides a convenient ingo#syntaxitem#IsOnSyntax( pos, syntaxItemPattern ) function for that.

    Also, check out the SyntaxAttr.vim - Show syntax highlighting attributes of character under cursor plugin. It is an indispensable debugging aid.