在VIM中折叠C预处理器

Sun*_*nny 6 vim folding

是否可以在VIM中折叠C预处理器.例如:

#if defined(DEBUG)
  //some block of code
  myfunction();
#endif
Run Code Online (Sandbox Code Playgroud)

我想折叠它,使它变成:

 +--  4 lines: #if defined(DEBUG)---
Run Code Online (Sandbox Code Playgroud)

DrA*_*rAl 1

由于 Vim 突出显示引擎的限制,这并非易事:它不能很好地突出显示重叠区域。在我看来,你有两个选择:

  1. 使用语法突出显示以及该contains=选项的更多信息,直到它适合您为止(可能取决于某些插件):

    syn region cMyFold start="#if" end="#end" transparent fold contains=ALL
    " OR
    syn region cMyFold start="#if" end="#end" transparent fold contains=ALLBUT,cCppSkip
    " OR something else along those lines
    " Use syntax folding
    set foldmethod=syntax
    
    Run Code Online (Sandbox Code Playgroud)

    这可能需要花很多功夫,而且你可能永远无法让它令人满意地工作。把这个放入vimfiles/after/syntax/c.vim~/.vim/after/syntax/c.vim

  2. 使用折叠标记。这会起作用,但您将无法折叠牙套或任何您可能喜欢的其他东西。将其放入~/.vim/after/ftplugin/c.vim(或 Windows 上的等效 vimfiles 路径):

    " This function customises what is displayed on the folded line:
    set foldtext=MyFoldText()
    function! MyFoldText()
        let line = getline(v:foldstart)
        let linecount = v:foldend + 1 - v:foldstart
        let plural = ""
        if linecount != 1
            let plural = "s"
        endif
        let foldtext = printf(" +%s %d line%s: %s", v:folddashes, linecount, plural, line)
        return foldtext
    endfunction
    " This is the line that works the magic
    set foldmarker=#if,#endif
    set foldmethod=marker
    
    Run Code Online (Sandbox Code Playgroud)