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

后端 未结 3 909
终归单人心
终归单人心 2020-12-31 09:29

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.

相关标签:
3条回答
  • 2020-12-31 10:04

    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
    
    0 讨论(0)
  • 2020-12-31 10:08

    Use gq, either over the whole selection with a VISUAL block, or with a movement, like gqq or gqj

    0 讨论(0)
  • 2020-12-31 10:13

    It has been included in Vim since V7.0 at least:

    See the following snippet from usr/share/vim/vim80/indent/python.vim (line 74) https://github.com/vim/vim/blob/master/runtime/indent/python.vim

    function GetPythonIndent(lnum)
      ...
      " When inside parenthesis: If at the first line below the parenthesis add
      " two 'shiftwidth', otherwise same as previous line.
      " i = (a
      "       + b
      "       + c)
      call cursor(a:lnum, 1)
      let p = searchpair('(\|{\|\[', '', ')\|}\|\]', 'bW',
          \ "line('.') < " . (a:lnum - s:maxoff) . " ? dummy :"
          \ . " synIDattr(synID(line('.'), col('.'), 1), 'name')"
          \ . " =~ '\\(Comment\\|Todo\\|String\\)$'")
      if p > 0
        if p == plnum
          " When the start is inside parenthesis, only indent one 'shiftwidth'.
          let pp = searchpair('(\|{\|\[', '', ')\|}\|\]', 'bW',
          \ "line('.') < " . (a:lnum - s:maxoff) . " ? dummy :"
          \ . " synIDattr(synID(line('.'), col('.'), 1), 'name')"
          \ . " =~ '\\(Comment\\|Todo\\|String\\)$'")
          if pp > 0
        return indent(plnum) + (exists("g:pyindent_nested_paren") ? eval(g:pyindent_nested_paren) : shiftwidth())
          endif
          return indent(plnum) + (exists("g:pyindent_open_paren") ? eval(g:pyindent_open_paren) : (shiftwidth() * 2))
        endif
        if plnumstart == p
          return indent(plnum)
        endif
        return plindent
      endif
      ...
    
    0 讨论(0)
提交回复
热议问题