set foldmethod=expr and use
'foldexpr' to set a vim script expression that will define the fold start points.
This looks more complicated than it is, because we can't easily use spaces in
:set, but with spaces, and a newline or 2, it looks like:
get(split(getline(v:lnum - 1)), 0, '') != get(split(getline(v:lnum)), 0, '')
\ ? '>1'
\ : '='
Basically this compares the first word of each line with the previous line. If the words are different then the line is start of the fold,
>1. Otherwise it keeps the same fold level,
Glory of Details
set foldmethod=expr to tell Vim to use a vim script expression to determine the foldings
'foldexpr' option holds the vim script expression
- Evaluating the condition with a ternary that returns
>1 when a fold should start and
= when the fold level should continue
v:lnum is the current line that that
'foldexpr' is running on to update the folds
- Get the contents the current line (
v:lnum) and the previous line (
v:lnum - 1) via
- Split each line into words via
get() to get the first index of the freshly split words
- Use a default value of
'' in case of a blank line. e.g.
get(words, 0, '')
- Compare the first word of the current line with the first word of the previous line in the condition portion of the ternary
Note: this method may have some performance issues with very large documents
For more help see: