突出显示游标下的代码块?

时间:2009-11-17 22:39:48

标签: syntax-highlighting vim

我正在寻找一种在正常模式下突出显示光标下当前代码块的方法。

这有点像set showmatch配置选项那样,但检测和突出显示会延伸到整个块。

使用配置选项还是(最好是现有的)脚本实现此功能的任何方法?

1 个答案:

答案 0 :(得分:1)

简答:不。

很长的回答:有很多方法可以实现这一目标,但你必须牺牲许多其他相当重要的突出功能。

使用简单的选项肯定无法做到这一点。您可能遇到的问题是Vim不允许重叠区域,因此如果您安装了rainbow.vim或在块区域中创建区域的任何其他内容,则会丢失。同样难以(虽然我欢迎任何更正)有多个突出显示的组,因此一个设置背景颜色,另一个设置前景。这是非常有限的,你会看到。

然而,如果喜欢玩,请继续阅读。

我在这里假设您使用与我相同编码风格的C代码,但这很容易改变......

这是一个简单的功能,可以帮助您了解所涉及的内容:

function! HighlightBlock()
    " Search backwards and forwards for an opening and closing brace
    " at the start of the line (change this according to your coding
    " style or how you define a block).
    let startmatch = search('^{', 'bcnW')
    let endmatch = search('^}', 'cnW')

    " Search in the other direction for each to catch the situation
    " where we're in between blocks.
    let checkstart = search('^{', 'cnW')
    let checkend = search('^}', 'bcnW')

    " Clear BlockRegion if it exists already (requires Vim 7 probably)
    try
        syn clear BlockRegion
    catch
    endtry

    " If we're not in a block, give up
    if ((startmatch < checkstart) && (endmatch > checkstart))
                \ || ((startmatch < checkend) && (endmatch > checkend))
                \ || (startmatch == 0)
                \ || (endmatch == 0)
        return
    endif

    " Create a new syntax region called "BlockRegion" that starts
    " on the specific lines found above (see :help \%l for more 
    " information).
    exec 'syn region BlockRegion'
                \ 'start=' . '"\%' . startmatch . 'l"'
                \ 'end='   . '"\%' . (endmatch+1)   . 'l"'

    " Add "contains=ALL" onto the end for a different way of 
    " highlighting, but it's not much better...

    " Define the colours - not an ideal place to do this,
    " but good for an example
    if &background == 'light'
        hi default BlockRegion guibg='#AAAAAA'
    else
        hi default BlockRegion guibg='#333333'
    endif

endfunction

要使用该功能,请从某处获取该功能,然后创建一个autocmd,以便在发生变化时调用它,例如

au CursorMoved *.c call HighlightBlock()

有关您可能需要考虑的一些自动命令,请参阅以下内容:

:help CursorHold
:help CursorHoldI
:help CursorMoved
:help CursorMovedI