python - Vim for Python 中的自动缩进

标签 python vim

我现在正在尝试切换到 VIM,并希望它像 IDE 对 Python 一样自动缩进。我有以下 .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

谁能帮我改正这个行为

最佳答案

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

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

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

filetype plugin indent on

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

关于python - Vim for Python 中的自动缩进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61435894/

相关文章:

vim - 在 VIM (ubuntu) 中,Nerdtree 未被识别为命令

vim - 如何在VIM中设置文件的字符编码

vim - 将 'find' 命令的输出重定向到 'vim'

python - 如何使用python icrawler爬取多个关键词

python - Twisted 中connectionLost 和clientConnectionLost 之间的区别

cursor - Vim:在终端中,我怎样才能拥有更好的光标?

vim - 为什么 Y 和 yy 做同样的事情?

python - 编译UWSGI Empire_mongodb插件

python - 获取与数据帧的另一个值最接近的值

python - aquamacs:在 C-c C-c 上切换窗口(python 模式)