Is there a way to make Vim fold functions based on the syntax of a function declaration?

For example having vim turn a function like this:

def foobar(foo,bar):
  if foo > bar:
    print "foo"
  elif foo < bar:
    print "bar"
  elif foo == bar:
    print "foobar"

Into this:

+----- 7 lines: def foobar(foo,bar): -------------------------------------------------------------

Is there some set of commands or a function I can put into my .vimrc file use to accomplish this?

3 Answers 3


Given that your example is in Python, which relies on correct indentation of code blocks it is enough to base folding on that:

:set foldmethod=indent

For more information on the varieties of folding available see :help foldmethod



set foldmethod=syntax

You can then use zc to close a fold, zo to open one, or za to toggle.

Unfortunately, Vim doesn't include folding information for Python by default, which you appear to be using. You could use one of many external resources, however.

  • 3
    In order for this to work the syntax file you are using should make use of syn-fold. in my installation of vim74, only about 10% of the syntax files use it.
    – jalanb
    Feb 6, 2015 at 0:15

This is my vimrc command to automatically fold a function pressing F4 when my cursor is placed on the function definition:

" fold whole function
nmap <silent> <F4> /{<CR>zfa}
  • Welcome to Vi and Vim! Note that you may want to consider using nnoremap. Also your mapping is specific to C-like/braces languages, while the OP specifically mentions other styles. Mentioning this caveat would probably improve the answer, as well as suggest possible ways to generalize. You can always edit to update and improve the answer.
    – D. Ben Knoble
    May 10, 2022 at 1:12

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.