2

For example, if I had source text like this (with the numbers on the left representing line numbers that are not part of the source text):

1  foo
2  bar
3
4  baz

it would appear as:

1  foo
2  bar
4  baz

To clarify, when I say "blank lines" I mean lines that would match the regex ^$.

3

Here is a possibility which uses foldexpressions:

fu! FoldEmptyLines(lnum)
    if !empty(getline(a:lnum)) && a:lnum+1 < line('$') && empty(getline(a:lnum+1))
        return 1
    elseif empty(getline(a:lnum))
        return '='
    else
        return 0
    endif
endfu
setl foldenable foldexpr=FoldEmptyLines(v:lnum) foldmethod=expr foldtext=getline(v:foldstart).repeat('\ ',winwidth(0)-len(split(getline(v:foldstart))))

This uses a foldexpression to check every line and decide whether the next line is empty. If it is, it will be marked as being inside of foldlevel 1. If the current line is already empty, use the previous foldlevel, else it isn't in a fold.

If you want to also fold lines, containing of only blanks, you would change the empty(getline(...)) part to empty(split(getline(...)))

To decide, how the folded line looks like, it uses the 'foldtext' setting and sets it explicitly to the text of the start of the folded line.

There are two problems with this approach. It will be probably slow for long files and second, you lose syntax highlighting for the folded lines.

2

You can do this with a feature called "Folds". Try adding this to your .vimrc:

syn match MyEmptyLines "\(^$\)\+" fold
syn sync fromstart
setlocal foldmethod=syntax

This tell's vim to create folds based off of the syntax of your file, and then adds a new syntax, e.g. any number of lines that match ^$. Then, you can fold all of these matches at once with zM, and unfold all of them with zR. You can also use za to expand the fold that is under your cursor. I have this in my .vimrc:

nnoremap <space> za
  • 2
    Folds work well for any multi-line blanks, but I wonder if there is a way to better handle single lines like in OP's example... – Tumbler41 Jul 14 '16 at 17:01
  • 2
    that does not work for single empty lines – Christian Brabandt Jul 14 '16 at 21:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.