I'd like to write a plugin that automatically sets the foldlevel of a newly opened document so that as much of the document fits on the screen as possible. (In other words, I'd like to make sure short documents open fully expanded while long documents open mostly collapsed.)

Is there any built-in function in vim that reports the number of visible lines in a document, given the current fold state or a particular fold level? (I.e., closed folds count as one line, but lines you'd have to scroll down to see are counted, too.)

1 Answer 1


Nice idea! Here's a basic function that achieves your goal using a different technique:

function! FitOnPage()
  normal! zR
  while &foldlevel > 0
    if line('w0') == 1 && line('w$') == line('$')
    normal! zm

It works by first expanding all the folds. It then closes folds (globally) until the entire document is on screen or all the folds are closed.

It checks if the whole file is on screen by checking if the first and last lines displayed are the first and last lines of the file.

You could improve this a bit by closing folds individually, but that would be a lot more complicated.

  • That's a clever alternative. I suppose if you really wanted to know how many visible lines there were over the whole document, you could do something like normal G | let i = 0 | while line('.') > 1 | normal k | let i += 1 | endwhile. Maybe I'll get around to tinkering with this this weekend. Thanks!
    – Ryan Lue
    Aug 5, 2017 at 16:34
  • @RyanLue I just updated my function to use the line() arguments you mentioned in your short-lived answer instead of moving the cursor.
    – Rich
    Aug 9, 2017 at 8:55
  • Ahahaha I quickly withdrew that answer after I realized it didn't really do what I wanted it to do in the first place. It's been a day of brainfarts. -_-'
    – Ryan Lue
    Aug 9, 2017 at 9:02
  • @RyanLue Might not have done what you wanted it to do, but it sure does what I want it to! ;)
    – Rich
    Aug 9, 2017 at 9:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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