From the multiple questions on various SE sites, I can disable all folding by e.g. putting set nofoldenable in ~/.vimrc. Is there a way to have folding enabled for large files, say >100 lines, and disabled for others? I mostly like folding but it's pointless when all code fits in a screen anyway.

2 Answers 2


I would do:

autocmd! BufRead * if line('$') < 100 | setlocal nofoldenable | else | setlocal foldenable | endif


  • The autocmd BufRead * trigers the corresponding code when the buffer is first read
  • The line('$') expression returns the number of lines of the buffer
  • If the number of line is below 100 the foldenable buffer option is disabled
  • Otherwise it is enabled

If you prefer to rely on the default value of the option when the buffer is large you could do:

autocmd! BufRead * if line('$') < 100 | setlocal nofoldenable | endif
  • 1
    The option is enabled or disabled, not set to yes or no.
    – romainl
    Commented May 27 at 11:47
  • 2
    @romainl feel free to edit improvements in
    – D. Ben Knoble
    Commented May 27 at 11:49
  • 1
    I'd rather have the author of the answer do it themselves.
    – romainl
    Commented May 27 at 11:56
  • 1
    cool thanks, exactly what I was looking for
    – ludog
    Commented May 27 at 12:36
  • Thanks for the feedback! I'm glad you have a solution to your problem. It is a nice suggestion I'm considering adopting it myself :-) Commented May 27 at 12:43

In addition to the autocommand in Vivian's answer that triggers exactly on 100 lines, there may be an easier way to achieve your goal.

Fold by modeline

To have folding enabled for specific files only, you can add a modeline (see: :help modeline) to your long file. This is typically a comment at the start or end of your file, e.g.:

A very long file
# vim: foldenable

Modelines come after autocommands (except BufWinEnter, see :help BufRead) and filetype plugin settings. They override the editor settings for one file.

Fold by filetype

If you know certain files will be very long, e.g. *.log files, you can just enable folding on a per-filetype basis.

The following line would go into your ~/.vim/after/ftplugin/log.vim (create it if it doesn't exist):

setlocal foldenable
  • the accepted answer is plenty easy imo, but thanks for the idea to make it dependent on file type, could potentially be useful to have both for certain cases, which would take precedence if used in conjunction with the line in ~/.vimrc?
    – ludog
    Commented May 27 at 12:45
  • @ludog the filetype settings are triggered by an autocommand and autocommands will execute in the order they were given (:help :autocmd). The modeline will come later (:help BufRead).
    – Friedrich
    Commented May 27 at 13:39

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.