Teaching vim to fold RStudio-like sections using foldexpr

262 views Asked by At

I would like to make the vim to honour rstudio-like sections and enable folding for those blocks of text through foldexpr.

Sections

The sections are fairly straightforward and correspond to blocks of text with a set of words and --- signs until 80 characters, as illustrated below:

RStudio sections as available on www.rstudio.com

Mor information on how the sections work is available here.

Problem

How can I built foldexpr in vim so it recognises a section of format:

# Word word ... ------------------------

regex

The regex matching section could be of format:

\#[[:blank:]]([[:word:]]|[[:blank:]]){1,}\-{1,}

regex101

1

There are 1 answers

1
Andrew Radev On BEST ANSWER

This seems to do the trick:

set foldmethod=expr
set foldexpr=RFoldexpr(v:lnum)

function! RFoldexpr(lnum)
  if getline(a:lnum) =~ '^#\s\(\w\+\s\+\)\+-\+$'
    " Start a new level-one fold
    return '>1'
  else
    " Use the same foldlevel as the previous line
    return '='
  endif
endfunction

Putting this in the file ~/.vim/ftplugin/r.vim should automatically evaluate it upon loading an R file. If you'd like to learn more about why it works and what other "features" you could add to it, try reading :help fold-expr.