【问题标题】:Autoindentation in Vim for PythonVim for Python 中的自动缩进
【发布时间】:2020-08-09 15:37:47
【问题描述】:

我现在正尝试切换到 VIM,并希望让它自动缩进,就像 Python 的 IDE 一样。我有以下 .vimrc 文件

syntax on

set number
autocmd FileType tex,latex,python set showmatch

nnoremap j gj
nnoremap k gk

"Python Settings
autocmd FileType python set softtabstop=4
autocmd FileType python set tabstop=4
autocmd FileType python set autoindent
autocmd FileType python set expandtab
autocmd FileType python set textwidth=80
autocmd FileType python set smartindent
autocmd FileType python set shiftwidth=4
autocmd FileType python map <buffer> <F2> :w<CR>:exec '! python' shellescape(@%, 1)<CR>
autocmd FileType python imap <buffer> <F2> <esc>:w<CR>:exec '! python' shellescape(@%, 1)<CR>

在某些情况下,代码会自动缩进。例如,我尝试过 if 语句和 while 语句,它们在按 Enter 后会缩进。所以下面会正确缩进。

if True:
    #this is where my next line automatically starts
while True:
    #this is where my next line automatically starts

但是对于类/函数定义,没有缩进。

class Request_Form(QDialog):
#no indentation -- cursor comes here

谁能帮我纠正这种行为

【问题讨论】:

  • 你检查过这个答案吗:stackoverflow.com/questions/65076/…
  • 如果你使用:filetype,它会回复indent:ON吗?编辑 Python 文件时,:set indentexpr? 是否回复 indentexpr=GetPythonIndent(v:lnum) 或类似的?
  • 看起来您正在从'smartindent' 获得缩进,这将(以及其他规则)在'cinwords' 中的单词之后缩进,默认为if,else,while,do,for,switch,这样就解释了您所看到的...但是'smartindent' 并不适合 Python,您需要使用 filetype indent on 加载每个文件类型的缩进规则,当您编辑 Python 源代码时,它应该为 Python 加载适当的缩进。
  • 谢谢你,@filbranden,为我做了这件事。
  • @Dargscisyhp 感谢您的确认!我将其发布为答案。

标签: python vim


【解决方案1】:

看起来您正在从'smartindent' 缩进,这将(除其他规则外,主要与花括号相关)在包含'cinwords' 列表中的单词的行之后缩进,默认为if,else,while,do,for,switch,因此似乎准确地解释了您当前所看到的内容。

但是'smartindent' 并不是真正适合 Python(正如您可以通过它处理花括号来猜测的那样。)相反,您需要使用 filetype indent on 来加载每个文件类型的缩进规则,该规则应该加载编辑 Python 源代码时为 Python 提供适当的缩进。

我建议你把它添加到你的 vimrc 中:

filetype plugin indent on

这应该可以为您解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    • 2011-06-03
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    相关资源
    最近更新 更多