Fold C Preprocessor in VIM
Is it possible to fold C preprocessor in VIM. For example:
开发者_Go百科#if defined(DEBUG)
//some block of code
myfunction();
#endif
I want to fold it so that it becomes:
+-- 4 lines: #if defined(DEBUG)---
This is non-trivial due to the limitations of Vim's highlighting engine: it cannot highlight overlapping regions very well. You have two options as I see it:
Use syntax highlighting and much about with the
contains=
option until it works for you (will depend on some plugins probably):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
This will probably take a lot of messing around and you may never get it working satisfactorily. Put this in
vimfiles/after/syntax/c.vim
or~/.vim/after/syntax/c.vim
.Use fold markers. This will work, but you won't be able to fold on braces or anything else that you might like. Put this in
~/.vim/after/ftplugin/c.vim
(or the equivalent vimfiles path on Windows):" 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
I've been able to get it working to my liking by adding these lines to my c.vim syntax file:
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")
精彩评论