【问题标题】:Vim: How to indent to an open paren or bracket when hitting enter?Vim:敲回车时如何缩进打开的括号或括号?
【发布时间】:2012-03-18 12:56:07
【问题描述】:

我用 Vim 编写 Python 已经有一段时间了,但有一件事我无法弄清楚如何将它设置为自动缩进到最后一个打开的括号的级别。

根据 pep8,如果您有一个开放的括号,并且您需要将行换行以适应 80 列,那么您应该在该开放的括号处继续下一行。示例:

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

显然这是一个疯狂的例子,但这就是你应该在 python 中打破你的行的方式。

我真正想做的是设置 Vim,这样当我输入 fit,<cr> 时,它会将我的光标放在打开括号右侧的下一行,所以我可以输入on, 等,而不是事先将 <tab><space> 键组合在一起。

我认为我永远不会相信 Vim 中 python 代码的自动格式化程序,但如果它也能工作的话,我会加分。

【问题讨论】:

标签: python vim pep8 auto-indent


【解决方案1】:

这可以稍微改进一下,但应该在 99% 的时间里都有效。在你的 .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

【讨论】:

    【解决方案2】:

    使用gq,在整个选区上使用VISUAL 块或移动,例如gqqgqj

    【讨论】:

      【解决方案3】:

      至少从 V7.0 开始就包含在 Vim 中了:

      请参阅usr/share/vim/vim80/indent/python.vim(第 74 行)https://github.com/vim/vim/blob/master/runtime/indent/python.vim 中的以下 sn-p

      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
        ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-29
        • 1970-01-01
        • 2021-01-17
        • 1970-01-01
        • 2022-07-22
        • 2022-11-12
        相关资源
        最近更新 更多