Is it possible to have vim highlight folds differently depending on whether every line in a fold is only comments or whitespace? In that case, how?

2 Answers 2


You cannot change the fold highlighting, as there's only one highlight group for all folds (:help hl-Folded). What you can do is indicate the "all comments"-nature of a fold via a custom fold-foldtext; for example, you could prepend COMMENTED:. It would then look like this:

+--  3 lines: # some stuff here

COMMENTED: +--  3 lines: # comment

command 2
command 3

The second part of a solution is determining whether all lines inside a fold are actually comments. This could be done by querying the syntax highlighting (via synID()), which would be universal, but also cumbersome and potentially slow. If all you care about is fully commented lines with a comment prefix, you could obtain that from 'comments' for the current filetype and manually match against it. (My ingo-library plugin has a function for that.) If all you care about is a simple, generic comment prefix like # (as used in shell scripts, Perl, etc.), a simple pattern match will do, like this:

function! CommentIndicator()
    for l:lnum in range(v:foldstart, v:foldend)
        if getline(l:lnum) !~# '^\s*#'
            " This fold is not fully commented.
            return ''
    return 'COMMENTED: '

let &foldtext = 'CommentIndicator() . foldtext()'

Yes, it is. Actually, you can use foldmethod=expr.

As an example:

set foldmethod=expr foldexpr=getline(v:lnum)=~'^\s*'.&commentstring[0]

You can see full answer with similiar problem here: [1].

  • Thanks for the answer, but as I understand it, this only lets me fold the comments selectively. I'm fine with the method of folding, but I would like to have the folded lines highlighted differently depending on whether they only constitute comments.
    – nijoakim
    Commented May 17, 2017 at 11:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .