14

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?

Martin Tournoij
  • 62,054
  • 25
  • 192
  • 271
Dom
  • 3,314
  • 5
  • 21
  • 38

3 Answers3

13

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

jalanb
  • 684
  • 7
  • 19
8

Sure:

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.

Doorknob
  • 15,237
  • 3
  • 48
  • 70
  • 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 06 '15 at 00:15
0

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.se]! 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 '22 at 01:12