在VIM中折叠C预处理器

时间:2010-03-09 09:34:20

标签: vim folding

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

#if defined(DEBUG)
  //some block of code
  myfunction();
#endif

我想折叠它以便它变成:

 +--  4 lines: #if defined(DEBUG)---

2 个答案:

答案 0 :(得分: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
    

    这可能会带来很多麻烦,你可能永远不会令人满意地工作。将其放在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
    

答案 1 :(得分:0)

我已经能够通过将这些行添加到我的c.vim语法文件中来实现它的工作:

syn match   cPreConditMatch display "^\s*\zs\(%:\|#\)\s*\(else\|endif\)\>"

+syn region cCppIfAnyWrapper  start="^\(%:\|#\)\s*\(if\|ifdef\|ifndef\|elif\)\s\+.*\s*\($\|//\|/\*\|&\)" end="^\s*\(%:\|#\)\s*endif\>" contains=TOP,cCppInIfAny,cCppInElseAny fold
+syn region cCppInIfAny  start="^\(%:\|#\)\s*\(if\|ifdef\|ifndef\|elif\)\s\+.*\s*\($\|//\|/\*\|&\)" end="^\s*\(%:\|#\)\s*\(else\s*\|elif\s\+\|endif\)\>"me=s-1 containedin=cCppIfAnyWrapper contains=TOP
+syn region cCppInElseAny  start="^\s*\(%:\|#\)\s*\(else\|elif\)" end="^\s*\(%:\|#\)\s*endif\>"me=s-1 containedin=cCppIfAnyWrapper contains=TOP

if !exists("c_no_if0")