Vim Python 缩进更改代码语义

2 投票
2 回答
1342 浏览
提问于 2025-04-17 08:20

我正在学习vim :-) 但是在自动缩进方面遇到了一些麻烦,这导致我的Python代码意思变了。有没有什么办法可以享受自动缩进的好处,而不出现下面这种情况呢?

我开始时有一个Python文件:

me@host:/tmp$ cat pytest.py 
if False:
    print('Never',
          'print this line')

print 'Always print this line.'

vim pytest.py 打开文件,然后输入 gg=G:wq 来自动缩进。

哎呀,我搞错了我的脚本:

me@host:/tmp$ cat pytest.py 
if False:
    print('Never',
            'print this line')

    print 'Always print this line.'

我尽量保持这个问题简单明了:

me@host:/tmp$ cat ~/.vimrc 
filetype plugin on
filetype indent on
autocmd FileType python set sw=4
autocmd FileType python set ts=4
autocmd FileType python set sts=4
autocmd FileType python set textwidth=79

2 个回答

4

嗯,别这么做。

在VIM编辑器中,自动缩进的主要目的是让编辑器根据编程语言的格式规则来猜测空格应该放在哪里。不过:

在这里输入图片描述

你知道,Python中的空格是非常重要的。就像医生会说的:别这么做。

2

在vim中让自动缩进正常工作,其实就是要确保你的tabstop、shiftwidth、softtabstop和expandtab这些设置和你正在编辑的文件一致。我使用了这个插件:

http://freecode.com/projects/vindect

这个插件会根据你正在编辑的python文件来调整这些设置,确保即使你在编辑其他人文件的时候,vim也能正确处理缩进,即使他们的空格设置和你不一样。

补充一下:如果你想对一个python源文件进行全面的重新缩进(也就是替代命令gg=G),你需要一个专门针对python的重新缩进工具,比如这个:http://svn.python.org/projects/doctools/trunk/utils/reindent.py,你可以很容易地把它变成一个vim命令。

撰写回答