By default, Vim will fold everything it can if folding is enabled. This can be useful from big complicated files, but it tends to get in the way for smaller, simpler files.

For example, if I open a code file that contains just one class, it makes no sense to have that class folded.

I think a reasonable metric for whether folding should happen, is the length of a file. If the file is much bigger than the terminal you're viewing it in, folding is probably beneficial. If it would (nearly) fit on a page unfolded, folding is probably more of a hindrance than a help.

Is there a way to make Vim only enable folding only if the file you're opening is longer than some size?


You can use the line() function to fold or unfold your file:

" In your vimrc

if line('$') > 20
   set foldlevel = 1

line('$') returns the line number of the last ($) line of your document.

Of course, this is executed only when you are launching Vim, so you can use a autocommand like so:

autocmd! BufReadPost * :if line('$') > 20 | set foldlevel=1 | endif
  • 2
    Sounds promising. I think it'd need to be combined with, say, BufRead to apply if I changed to edit a different file – SpoonMeiser Jul 8 '16 at 10:41
  • You read in my mind, see my edit ;) – nobe4 Jul 8 '16 at 10:43

Another way to do this, as you specified:

if I open a code file that contains just one class [...]

You can count the number of classes in your file and act based on the result:

:let n=[0] | %s/^class/\=map(n,'v:val+1')[1:]/gen | if n[0] > 1 | set foldlevel=1 | endif


let n=[0]                Create an array to be filled with the number of occurence
%s/^class/               Substitute on all lines for the word class starting a line
\=map(n,'v:val+1')[1:]   Increment the n value on each found class
/en                      Don't move the cursor, and don't actually substitute

The remaining is just a condition, like my other response. You can also use an autocommand for this.

The count method comes from Stack Overflow question Using Vim, how do you use a variable to store count of patterns found?.

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.