CoolWind
CoolWind

Reputation: 1

How to fold "#if ... #endif", but skip "{" in between?

I add this line to ~/.vimrc to fold C macro #if ... #endif:

au FileType h,c,cpp syn region zhouzmFoldIf start="^\s*#if" end="^\s*#endif" fold transparent extend

It works well most of the time. But if there is a { in between, it can't fold correctly. How can I solve this problem?

Upvotes: 0

Views: 378

Answers (1)

Ingo Karkat
Ingo Karkat

Reputation: 172510

In this vim_use thread, the problem is discussed. Ben Fritz posted the following solution.

" fold #if...#else...#endif constructs
syn region IfFoldContainer
    \ start="^\s*#\s*if\(n\?def\)\?\>"
    \ end="#\s*endif\>"
    \ skip=+"\%(\\"\|[^"]\)\{-}\\\@<!"\|'[^']\{-}'\|'\\''\|//.*+
    \ transparent
    \ keepend extend
    \ containedin=NONE
    \ contains=SynFoldIf,SynFoldElif,SynFoldElse
syn region SynFoldIf
    \ start="^\s*#\s*if\(n\?def\)\?\>"
    \ end="^\s*#\s*el\(se\|if\)\>"ms=s-1,me=s-1
    \ skip=+"\%(\\"\|[^"]\)\{-}\\\@<!"\|'[^']\{-}'\|'\\''\|//.*+
    \ fold transparent
    \ keepend
    \ contained
    \ nextgroup=SynFoldElif,SynFoldElse
    \ contains=TOP
syn region SynFoldElif
    \ start="^\s*#\s*elif\>"
    \ end="^\s*#\s*el\(se\|if\)\>"ms=s-1,me=s-1
    \ skip=+"\%(\\"\|[^"]\)\{-}\\\@<!"\|'[^']\{-}'\|'\\''\|//.*+
    \ fold transparent
    \ keepend
    \ contained
    \ nextgroup=SynFoldElse
    \ contains=TOP
syn region SynFoldElse
    \ start="^\s*#\s*else\>"
    \ end="^\s*#\s*endif\>"
    \ skip=+"\%(\\"\|[^"]\)\{-}\\\@<!"\|'[^']\{-}'\|'\\''\|//.*+
    \ fold transparent
    \ keepend
    \ contained
    \ contains=TOP

Upvotes: 4

Related Questions