Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim: How to indent to an open paren or bracket when hitting enter?

I've been programming Python with Vim for a while but one thing I haven't been able to figure out how to do it set it to auto indent to the level of the last open paren.

According to pep8 if you have an open paren and you need to break the line to fit in 80 columns then you're supposed to continue the next line at that open paren. Example:

calling_some_really_long_function(that, has, way, too, many, arguments, to, fit,
                                  on, one, line)

Obviously this is a crazy example, but that's how you're supposed to break your lines in python.

What I'd really like to be able to do is set up Vim so that when I type fit,<cr> and it will place my cursor on the next line just to the right of the open paren, so I can just type on, etc. instead of some combination of <tab> and <space> keys beforehand.

I don't think I'll ever trust the auto-formatter for python code in Vim but bonus points if that works too.

like image 591
William Avatar asked Feb 29 '12 01:02

William


1 Answers

This can be refined a bit, but should work 99% of the time. Add this in your .vimrc:

function! PythonEnterFunc()
  let l:li = getline('.')
  execute "normal! a\<Cr>"
  if l:li =~ '([^)]*$'
    let l:pos = stridx(l:li, '(') + 1
    for i in range(l:pos)
      execute "normal! a\<Space>"
    endfor
  endif
endfunction

au FileType python inoremap <Cr> <Esc>:call PythonEnterFunc()<CR>a
like image 200
Xavier Nicollet Avatar answered Sep 27 '22 16:09

Xavier Nicollet