Search code examples
regexvimhighlighttext-cursor

Vim script highlight regex matches on cursor line


I'm trying to apply highlighting to all regular expression matches only on the cursor's line. This code is close but I have to redraw the screen with every time the cursor moves, and it makes the cursor a part of the regex which is not ideal.

~/.vim/syntax/abc.vim:
syn match abcline      "abc\%#"
hi def link abcline    Todo

Solution

  • Your approach with the special \%# is correct. Unfortunately, its :help explicitly warns about the necessary redraw (which isn't done automatically for performance reasons).

    \%# Matches with the cursor position.
            WARNING: When the cursor is moved after the pattern was used, the
            result becomes invalid.  Vim doesn't automatically update the matches.
            This is especially relevant for syntax highlighting and 'hlsearch'.
            In other words: When the cursor moves the display isn't updated for
            this change.  An update is done for lines which are changed (the whole
            line is updated) or when using the |CTRL-L| command (the whole screen
            is updated).
    

    So, you need an :autocmd CursorMoved,CursorMovedI to trigger a redraw. Alternatively, you could embed the current line number into the regular expression (\%23l), and update the syntax definition as the cursor moves around (again via :autocmd). I'm no fan of such frequent redraws; perhaps your use case would also allow to just trigger the highlighting on demand (via a mapping), or only updates when the uses pauses (CursorHold[I] events).

    Doing syntax highlighting only for the current line is unusual; also reconsider whether a global highlighting would work (if you tone down the used highlight group; especially Todo is very visually distracting).