Search code examples
vimsyntaxregionfold

How can I use Vim syntax files to collapse single line comments into one region?


I'm putting together a syntax for editing Java Manifest files (at github, if anyone's interested). I'm trying to collapse multiple single-line-comments (which I'm matching at the moment with syntax match manifestComment "#.*"). However, if I try to use a syntax region, then the entire file is marked and the entire thing collapses.

What I'm trying to achieve is this:

# A comment
# Another comment
# A third comment
Manifest-Version: 1

and have it collapse down into:

+--  3 lines: # A comment ----
Manifest-Version: 1 

The problem is that there's no distinct 'end' character, and the fold syntax doesn't help; so I can't do syntax region commentBlock start="^#" end="^[^#]". Roughly, the syntax region should start from the first hash character, and then continue down the lines until it finds a line which doesn't begin with a hash.


Solution

  • :set foldmethod=expr
    :set foldexpr=getline(v:lnum)[0]==\"#\"
    

    For information, :h fold-expr.