15

在编写 C 代码时,我混合使用GNUK&R风格。这意味着函数的返回值、每个参数和左花括号都在自己的行上。我也想使用 Vim 的折叠功能,但是使用foldmethod=syntax,折叠看起来像这样:

折叠不良

是否可以在没有任何特殊折叠标记或 s 的情况下在折叠摘要中看到函数名称foldexpr

4

3 回答 3

2

可能是一个很好的折衷方案 - 如果您使用indent折叠 - 将foldminlines参数设置为更高的数字。

:set foldmethod=indent
:set foldminlines=5

如果你的大部分函数都很长,它只会影响你的参数列表。缺点显然是,它还会自动展开小于 5 行长的小功能。

于 2013-01-26T04:09:59.683 回答
1

试试这个作为起点(我在我的 vimrc 中有它,但我在网上找到了它):

" Folding {
function! CssFoldText()
    let line = getline(v:foldstart)
    let nnum = nextnonblank(v:foldstart + 1)
    while nnum < v:foldend+1
        let line = line . " " . substitute(getline(nnum), "^ *", "", "g")
        let nnum = nnum + 1 
    endwhile
    return line
endfunction

setlocal foldtext=CssFoldText()
setlocal foldmethod=marker
setlocal foldmarker={,}
setlocal fillchars=fold:/
setlocal foldlevel=-1
"   highlight Folded term=underline cterm=bold gui=bold guifg=Blue guibg=Black
"   highlight FoldColumn term=underline cterm=bold gui=bold guifg=Blue guibg=Black
"}
于 2012-11-19T23:13:48.433 回答
0

也可以通过语法折叠来做到这一点。您需要将以下内容添加到~/.vim/after/syntax/c.vim

let s:contains = ''
if exists("c_curly_error")
  let s:contains = ' contains=ALLBUT,cBadBlock,cCurlyError,@cParenGroup,cErrInParen,cErrInBracket,@cStringGroup,@Spell'
endif

let s:pattern = '%('

if &ft ==# "cpp"
  " struct/class inheriting
  let s:pattern .= ''
        \ . '%(<struct|<class)@<='
        \ . '\s\ze\s*\S+[^:]:[^:]\s*\S+.*'
  let s:pattern .= '|'

  " Constructors
  let s:pattern .= ''
        \ . '%('
        \ .    '%([^,:]|\n|^|<%(public|private|protected)>\s*:)'
        \ .    '\n\s*'
        \ . ')@<='
        \ . '%(<%(while|for|if|switch|catch)>)@!'
        \ . '\S\ze\S*%(::\S+)*\s*\(.*\)\s*%(:.*)?'
  let s:pattern .= '|'
endif

let s:pattern .= '%(<%(while|for|if|switch|catch)\(.*)@<=\)\ze\s*' . '|'

let s:pattern .= ''
      \ . '%('
      \ .    '^\s*%(//.*|.*\*/|\{|<%(public|private|protected)>\s*:|.*\>)?'
      \ .    '\s*\n\s*\S+'
      \ . ')@<='
      \ . '\s\ze\s*\S+\s*'
      \ . '%(.*[^:]:[^:].*)@!'
      \ . '%(\s+\S+)*'

let s:pattern .= ')%(;\s*)@<!%(//.*|/\*.*\*/)?\n\s*'

syn clear cBlock
exec 'syn region cBlock_ end="}" fold' . s:contains
      \ . ' start = "\%#=1\C\v' . s:pattern . '\{"'
      \ . ' start = "\%#=1\C\v%(' . s:pattern . ')@<!\{"'

unlet s:contains s:pattern

但请注意,如果文件很大,重新计算折叠可能会非常繁重。

于 2020-12-11T13:43:35.340 回答