Vim:当按enter键时,如何缩进一个开括号或括号?

2024-10-02 18:23:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Vim编程Python有一段时间了,但有一件事我还没弄明白怎么做,把它设置为自动缩进到上一个openparen的级别。在

根据pep8,如果你有一个开放的paren,你需要把这条线分成80列,那么你应该在这个开放的paren上继续下一行。示例:

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

显然,这是一个疯狂的例子,但这正是您在python中应该如何中断行的。在

我真正想做的是设置Vim,这样当我输入fit,<cr>时,它会将我的光标放在打开paren右边的下一行,这样我就可以只键入on,等,而不是事先组合使用<tab>和{}键。在

我不认为我会信任Vim中python代码的自动格式化程序,但是如果它也能工作的话,那就有好处了。在


Tags: 示例on编程functionsomevim级别long
3条回答

使用gq,可以使用可视块覆盖整个选择,也可以使用移动,如gqq或{}

这可以改进一点,但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

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

请参阅以下来自usr/share/vim/vim80/indent/python.vim(第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
  ...

相关问题 更多 >