Vim folds

From wikinotes

vim code-folding lets you navigate your code more quickly.
There are a handful of methods you can fold:

  • indentation
  • expressions
  • syntax
  • diffs
  • markers

Documentation

:h fold https://vimhelp.org/fold.txt.html

keymaps

zR  " unfold all
zM  " fold all

zc  " fold text under cursor
zo  " unfold text under cursor
zO  " unfold text under cursor recursively

options

set foldlevel=0  " fold everything

foldtext

foldtext allows you to customize what information is displayed within the fold.

function! GetLangFoldText()
    let foldsize = (v:foldend - v:foldstart)  " num lines in fold
    let text = getline(v:foldstart)           " text on first line of fold
    return text .' ('. foldsize .' lines)'
endfunction

set foldtext=GetLangFoldText()

foldmethod

syntax

when your foldmethod is set to syntax, you are using regex values outlined within that language's syntax file to determine where a fold belongs.

Example:

syntax region javadocFold start=+/\*+ end=+\*/+ transparent fold keepend extend
syntax region foldBraces  start=/{/ end=/}/     transparent fold keepend extend

The fold indicated after the regex match indicates that this region should get folded.

expr

NOTE:

Incomplete. This can get very tricky.

'-1'   # line's foldlevel is smallest of last-line/next-line
'='    # same foldlevel as last-line

'1'    # numbers > 0 are the fold-level
'>1'   # end last fold, start a new level-1 fold
setlocal foldmethod=expr
setlocal foldexpr=GetLangFold(v:lnum)

function! GetLangFold(lnum)
    " blank line
    if getline(a:lnum) =~ '^\s*$'
        return '-1'
    endif
endfunction

See excellent http://learnvimscriptthehardway.stevelosh.com/chapters/49.html