Python 版 Vim 中的自动缩进

Dar*_*yhp 3 python vim

我现在正在尝试切换到 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>
Run Code Online (Sandbox Code Playgroud)

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

if True:
    #this is where my next line automatically starts
Run Code Online (Sandbox Code Playgroud)
while True:
    #this is where my next line automatically starts
Run Code Online (Sandbox Code Playgroud)

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

class Request_Form(QDialog):
#no indentation -- cursor comes here
Run Code Online (Sandbox Code Playgroud)

谁能帮我纠正这种行为

fil*_*den 6

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

'smartindent'对于 Python 来说并不是那么合适(你可以通过它处理大括号来猜测)。相反,你需要使用它filetype indent on来加载每个文件类型的缩进规则,当你编辑 Python 源代码时,它应该为 Python 加载适当的缩进。

我建议你将其添加到你的 vimrc 中:

filetype plugin indent on
Run Code Online (Sandbox Code Playgroud)

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