代码之家  ›  专栏  ›  技术社区  ›  julien

在光标代码块下突出显示?

  •  2
  • julien  · 技术社区  · 15 年前

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

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

    使用配置选项或(最好是现有的)脚本实现此功能的方法是什么?

    1 回复  |  直到 15 年前
        1
  •  1
  •   DrAl    15 年前

    简短回答:不。

    答案很长:有很多方法可以做到这一点,但是你必须牺牲很多其他相当重要的突出显示功能。

    当然,用一个简单的选择是没有办法做到这一点的。你可能会遇到的问题是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