A S
A S

Reputation: 1235

How to write a foldexpr for Vim that would use the comments structure?

Is it possible to construct a foldexpr that would detect the following matches \n\n"\s[A-Z][A-Z].*\n as a start for first-level folds, and these matches \n"\s[A-Z][a-z].*\n as a start for second-level folds? Naturally, the nearest possible \n\n\n would mark an end of a first-level fold, and then \n\n would close the second-level fold.

Or am I missing something?

(I surely know about {{{ markers, it just doesn't seem right to my adding additional markers to a file...)

Upvotes: 0

Views: 456

Answers (1)

Ben
Ben

Reputation: 8905

You won't be able to do this (at least, not easily or clearly) in a one-liner. You'll want to write a function.

Your function will not be able to use a single getline() plus regex compare, because getline() only returns a single line and you want to include multiple lines in your start/end strings. You can however, use multiple getline() calls and compare each line separately.

To enable starting new folds at the same level of a currently existing fold, you'll need to return strings ">1" or ">2". For ending folds, it is probably easiest to just set an explicit level (using strings "<2", etc. sometimes acts unexpectedly for me). See :help fold-expr for possible return values. It may be useful to know the last line's foldlevel in your function. For that, use the function foldlevel().

Here is an example which I think does what you ask for, though you may need to clean it up if it's not actually what you want. Load the script, source it, and it can use itself as test data:

fun! FoldSomething(lnum)
  let line1=getline(a:lnum)
  let line2=getline(a:lnum+1)
  if line1=~'^$'
    if line2=~#'^"\s[A-Z][A-Z]'
      return ">1"
    elseif line2=~'^$'
      return 0
    elseif foldlevel(a:lnum-1)==2
      return 1
    endif
  elseif line1=~#'^"\s[A-Z][a-z]'
    return ">2"
  endif
  return "="
endfun
set foldexpr=FoldSomething(v:lnum)
set foldmethod=expr
set foldcolumn=3
finish


" AA level 1 fold
" This is a level 2 fold
Here is some stuff under the fold.
It should be part of the level 2.

This isn't in the level 2.
I guess that makes it just part of the level 1.

" This is another
" level 2 fold.
" Watch out!
" This is 2 level 2 folds.


" BB another level 1 fold
" starts here.
"



This line shouldn't be folded at all.

That's because there were so many empty lines before.

Upvotes: 1

Related Questions