Vim 脚本突出显示光标行上的正则表达式匹配项

Vim script highlight regex matches on cursor line

我正在尝试将突出显示应用于仅在光标行上的所有正则表达式匹配项。这段代码很接近,但每次光标移动时我都必须重新绘制屏幕,​​并且它使光标成为不理想的正则表达式的一部分。

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

您使用特殊 \%# 的方法是正确的。不幸的是,它的 :help 明确警告必要的重绘(出于性能原因不会自动完成)。

\%# 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).

因此,您需要 :autocmd CursorMoved,CursorMovedI 来触发重绘。或者,您可以将当前行号嵌入到正则表达式 (\%23l) 中,并在光标四处移动时更新语法定义(再次通过 :autocmd)。我不喜欢如此频繁的重绘;也许您的用例还允许只触发按需突出显示(通过映射),或者仅在使用暂停时更新(CursorHold[I] 事件)。

只对当前行进行语法高亮是不寻常的;还要重新考虑全局突出显示是否有效(如果你淡化使用的突出显示组;特别是 Todo 在视觉上非常分散注意力)。