I want to fold all special documentation comments, and only all special documentation comments. To do that I created a new syntax, doxygenComment and added highlighting (in red, just to test it). The comments are getting highlighted correctly, but my GetCppFold doesn't seem to work, since no comments are getting folded:

augroup filetype_cpp

    " Create custom doxygen comment style
    autocmd FileType cpp syn region doxygenComment start="/\*\!" end="\*/"
    autocmd FileType cpp hi link doxygenComment cError

    " Fold comments.
    autocmd FileType cpp setlocal foldmethod=expr
    autocmd FileType cpp setlocal foldexpr=GetCppFold(v:lnum)

    " Close all folds.
    autocmd BufRead *.cxx,*.hxx,*.cpp,*.hpp normal zM
augroup END

The following function simply checks whether the line is considered a doxygenComment or not, and returns the appropriate fold level. Keep in mind, I don't want any additional indent/syntax folding. I only want the comments folded (technically, I would want to have the functions folded, too, but this seems to be quite hard, since the syntax can't decipher between function and namespace or classes).

function! GetCppFold(lnum)
    let line = getline(a:lnum)

    " Check whether the line is empty or whitespace only.
    if line =~? '\v^\s*$'
        return '-1'

    let a:data = join(map(synstack(a:lnum, 1), 'synIDattr(v:val, "name")'))
    if a:data =~? ".*omment.*"
        echo "match"
        return '='

    return '-1'
  • I don't think there's a local foldlevel but try set foldlevel=2 or similar in the augoup. – Steve May 7 '18 at 2:52
  • Sorry on my previous comment which I can't edit set foldlevel=0, perhaps, outside this function and only set to 2 for this augroup. You'd need to do it on a BufRead etc. – Steve May 7 '18 at 4:17

You're only returning two different values from your function:

  • -1: the fold level is undefined, use the fold level of a line before or after this line, whichever is the lowest.
  • =: use fold level from the previous line

If you want the function to work, you're going to need to return an actual fold level at some point.

(Also, you're returning -1 as a string—I think it should be a number.)

autocmd FileType cpp syntax region doxygenComment start="/\*\!" end="\*/" fold
autocmd FileType cpp syntax sync fromstart
autocmd FileType cpp setlocal foldmethod=syntax

See :help syn-fold.

You may be able to use syntax sync ccomment doxygenComment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.