使用Vim打造现代化的Python IDE

来源:转载

转载目的:方便使用!!
使用Vim打造现代化的Python IDE

目录
介绍
基本的编辑和调试
代码折叠
窗口拆分
代码切片
任务列表
修订历史
语法高亮和验证
PEP8
Tab补全和文档
代码导航
缓冲区
模糊搜索
文件浏览
重构和跳转
搜索
Git集成
测试集成
Django nose
py.test
Diango
Virtualenv
Django
其他小技巧
本文所有操作的代码可在Github上下载,使用方法为:
123$
git clone https:
//github.com/sontek/dotfiles.git$ cddotfiles$
.
/install.sh
vim

下载PDF版本

介绍


Back in 2008, I wrote the article Python with a modular IDE (Vim). Years later, I have people e-mailing me and commenting daily asking for more information, even though most of the information in it is outdated. Here is the modern way to work with Python and Vim to achieve the perfect environment.
早在2008年,我写了一篇文章, 一个模块化的Python IDE(VIM) 。多年以后,文中的大部分信息都已经过时了,但还有很多人向我发送电子邮件询问更多的信息。本文的目的就是要使用Vim打造一个适合Python开发的完美环境。
Because one of the most important parts about a development environment is the ability to easily reproduce across machines, we are going to store our vim configuration in git:
由于开发环境的一个重要特性就是可以很容易的在不同机器间复制,因此我们将自己的vim配置放到了git上:
1234$
mkdir ~
/.vim/$
mkdir ~
/.vim/{autoload,bundle}$
cd ~
/.vim/$
git init

The purpose of the autoload directory is to automatically load the vim plugin Pathogen, which we'll then use to load all other plugins that are located in the bundle directory. So download pathogen and put it in your autoload folder.
autoload目录用来自动加载vim扩展Pathogen ,而这个扩展用来加载bundle目录中的其他所有扩展。所以你现在需要下载Pathogen扩展,并将其放到autoload目录中。
You'll need to add the following to your ~/.vimrc so that pathogen will be loaded properly. Filetype detection must be off when you run the commands so its best to execute them first:
为了正确加载pathogen,你需要在~/.vimrc中加入以下几行命令。当运行pathogen命令的时候文件格式检测必须关闭,所以最后把filetype off放到最前面:
12filetype
off call pathogen
#runtime_append_all_bundles()call
pathogen
#helptags()

Now lets add all of the vim plugins we plan on using as submodules to our git repository:
现在,我们把所有打算使用的vim扩展加到git仓库中:
123456789101112131415161718192021git
submodule add http:
//github.com/tpope/vim-fugitive.git
bundle
/fugitivegit
submodule add https:
//github.com/msanders/snipmate.vim.git
bundle
/snipmategit
submodule add https:
//github.com/tpope/vim-surround.git
bundle
/surroundgit
submodule add https:
//github.com/tpope/vim-git.git
bundle
/gitgit
submodule add https:
//github.com/ervandew/supertab.git
bundle
/supertabgit
submodule add https:
//github.com/sontek/minibufexpl.vim.git
bundle
/minibufexplgit
submodule add https:
//github.com/wincent/Command-T.git
bundle
/command-tgit
submodule add https:
//github.com/mitechie/pyflakes-pathogen.gitgit
submodule add https:
//github.com/mileszs/ack.vim.git
bundle
/ackgit
submodule add https:
//github.com/sjl/gundo.vim.git
bundle
/gundogit
submodule add https:
//github.com/fs111/pydoc.vim.git
bundle
/pydocgit
submodule add https:
//github.com/vim-scripts/pep8.git
bundle
/pep8git
submodule add https:
//github.com/alfredodeza/pytest.vim.git
bundle
/py.testgit
submodule add https:
//github.com/reinh/vim-makegreenbundle/makegreengit
submodule add https:
//github.com/vim-scripts/TaskList.vim.git
bundle
/tasklistgit
submodule add https:
//github.com/vim-scripts/The-NERD-tree.git
bundle
/nerdtreegit
submodule add https:
//github.com/sontek/rope-vim.git
bundle
/ropevimgit
submodule init
git
submodule update
git
submodule foreach git submodule init
git
submodule foreach git submodule update

Thats it! Now that we've got our vim configuration in git!
搞定!现在,我们已经将vim配置放到了git仓库中。
Now lets look at how to use each of these plugins to improve the power of vim:
现在,我们来看看如何使用这些扩展来增强vim:

基本的编辑和调试


====代码折叠====
Lets first enable code folding. This makes it a lot easier to organize your code and hide portions that you aren't interested in working on. This is quite easy for Python, since whitespace is required.
让我们先启用代码折叠。代码折叠使得代码组织和隐藏不感兴趣代码变得容易。由于Python使用空白来对齐,所以对Python来说使用起来也很容易。
In your ~/.vimrc just add:
在你的~/.vimrc中只需添加以下两行:
12setfoldmethod=indentsetfoldlevel=99

Then you will be able to be inside a method and type 'za' to open and close a fold.
然后,将光标定位到一个方法内部,就可以使用'za‘来打开和折叠代码了。
====窗口拆分====
Sometimes code folding isn't enough; you may need to start opening up multiple windows and working on multiple files at once or different locations within the same file. To do this in vim, you can use these shortcuts:
仅有代码折叠是不够的。有时,你可能需要同时打开多个窗口或者同时编辑一个文件的多个位置。在vim中要做到这一点,你可以使用下面这些快捷键:
123垂直拆分:按Ctrl
+ W + V
水平拆分:按Ctrl
+ W + S
关闭当前窗口:按Ctrl
+ W + Q

I also like to bind Ctrl+ keys to move around the windows, instead of using Ctrl+w + :
我习惯绑定Ctrl + 键来在不同窗口之间移动,而不是使用CTRL + W +
1234map
j
map
k
map
l
map
h


====代码切片====
The next tweak that really speeds up development is using snipmate. We've already included it in our bundle/ folder so its already enabled. Try opening up a python file and typing 'def'. It should stub out a method definition for you and allow you to tab through and fill out the arguments, doc string, etc.
下一个真正加快开发速度的调整是使用代码切片。我们已经把它放到了bundle文件夹中,所以它已经是启用状态了。打开一个python文件,然后输入"def"。就会弹出一个选择框,你可以通过tab键来选择函数参数、函数文档等。
I also like to create my own snippets folder to put in some custom snippets:
我也习惯创建自己的代码片段文件夹,来放一些自定义的代码片段:
12$ mkdir~/.vim/snippets$
vim ~/.vim
/snippets/python.snippets

Put this in the file:
将下面的内容保存到文件中:
12snippet
pdb
importpdb;
pdb.set_trace()

Now you can type pdb and it'll insert your breakpoint!
现在,您可以通过键入pdb来插入上面的代码片段。
====任务列表====
Another really useful thing is to mark some of your code as TODO or FIXME! I know we all like to think we write perfect code, but sometimes you just have to settle and leave a note for yourself to come back later. One of the plugins we included was the tasklist plugin that will allow us to search all open buffers for things to fix. Just add a mapping to open it in ~/.vimrc:
另一个非常有用的调整是标记某些代码为TODO或FIXME!我知道大家都这样想:我编写的代码是完美的。但有时有些未解决问题需要标记一下稍后再来解决。我们所安装的插件之一——plugin插件可以帮助我们在所有打开的文件中搜索这些标记的问题。只需要在~/.vimrc中添加一个映射:
1map
td TaskList

Now you can hit td to open your task list and hit 'q' to close it. You can also hit enter on the task to jump to the buffer and line that it is placed on.
现在,你可以键入td打开您的任务列表,并键入“q”将其关闭。您也可以在任务上键入回车键跳转到它所在的代码行。
====修订历史====
The final basic editing tweak I suggest everyone start utilizing is the Gundo plugin. It'll allow you to view diff's of every save on a file you've made and allow you to quickly revert back and forth:
最后一个基本编辑的调整是:我建议大家开始使用Gundo插件。它允许您查看文件每次保存之间的差别,并可以快速的回滚和恢复。

Just bind a key in your .vimrc to toggle the Gundo window:
在vimrc绑定一个键来打开Gundo窗口:
1map
g :GundoToggle

语法高亮和验证


Simply enable syntax highlighting in your ~/.vimrc:
在~/.vimrc文件中增加以下几行来开启语法高亮:
123syntax
on " syntax highlighing
filetype
on " try to detect filetypes
filetype
plugin indent on "
enableloading
indent
fileforfiletype

Because we enabled pyflakes when we added it as a submodule in ~/.vim/bundle, it will notify you about unused imports and invalid syntax. It will save you a lot of time saving and running just to find out you missed a colon. I like to tell it not use the quickfix window:
我们在~/.vim/bundle中启用了pyflakes插件,它会在代码中有未使用的import和语法错误时通知你。它会为你节省很多的时间来保存和运行代码,而这只是为了找到你漏掉的一个冒号。我想告诉它不使用quickfix窗口:
1letg:pyflakes_use_quickfix
= 0


====PEP8====
The final plugin that really helps validate your code is the pep8 plugin, it'll make sure your code is consistent across all projects. Add a key mapping to your ~/.vimrc and then you'll be able to jump to each of the pep8 violations in the quickfix window:
最后,真正可以帮助你验证代码的插件是PEP8,它会确保你的代码在所有项目中是一致的。在你的~/.vimrc中添加一个映射,然后,你就可以在quickfix窗口中调转到每个违反PEP8的位置:
1letg:pep8_map='8'


Tab补全和文档


Vim has many different code completion options. We are going to use the SuperTab plugin to check the context of the code you are working on and choose the best for the situation. We've already enabled the SuperTab plugin in the bundle/ folder, so we just have to configure it to be context sensitive and to enable omni code completion in your ~/.vimrc:
Vim有很多不同的代码补全选项。我们将使用SuperTab插件来检查并补全代码。我们已经在bundle文件夹中启用了SuperTab插件,所以我们只需要配置它是上下文相关并开启代码补全即可。在~/.vimrc中添加:
12au
FileType python
setomnifunc=pythoncomplete#Completeletg:SuperTabDefaultCompletionType
=
"context"

Now we just enable the menu and pydoc preview to get the most useful information out of the code completion:
现在,开启菜单和pydoc预览,以获得代码补全时最有用的相关信息:
1setcompleteopt=menuone,longest,preview


We also enabled the pydoc plugin at the beginning with all the submodules; that gives us the ability to hit pw when our cursor is on a module and have a new window open with the whole documentation page for it.
我们还在所有子模块中启用了的pydoc插件,这样,当光标在一个模块名上时,键入pw就可以在一个新窗口中打开这个模块的文档。

代码导航


====缓冲区====
The most important part about navigating code within vim, is to completely understand how to use buffers. There is no reason to use tabs. Open files with :e to place in a buffer. We already installed the minibufexpl plugin, so you will already visually see every buffer opened. You can also get a list of them doing :buffers.
要想在Vim内导航代码,最重要是要完全理解如何运用缓冲区。我们没有理由使用tab键。用e: <文件名> 打开文件,并放到缓冲区中。我们已经安装了minibufexpl插件,这样你就可以直观地看到每个打开的缓冲区。您还可以通过:buffers得到它们的列表。
You can switch between the buffers using b, such as :b1 for the first buffer. You can also use its name to match, so you can type :b mod to autocomplete opening the models.py buffer. You need to make sure you are using the minibufexpl from my github since it has patches that make it much better to work with.
通过b <数字>切换缓冲区,如:b1切换到第一个缓冲区。在切换的时候,你还可以使用缓冲区的名字匹配,所以你可以输入:b mod键来自动完成打开的models.py缓冲。要确保从从我的github上下载minibufexpl,因为它对原版minibufexpl打了很多补丁,比原版的更好用。
To close a buffer you use :bd or :bw.
要关闭一个缓冲区,你可以使用:bd或:bw。
====模糊搜索====
To make finding and opening files within your project even easier, we are going to use the command-t plugin. It does have some parts that need to be compiled, so its not already installed by adding it as a submodule. Go to your ~/.vim/bundle/command-t folder and run 'rake make'. Yes you need ruby installed. By default, command-t is bound to t. This will use fuzzy text matching to find any file in your project.
为了更容易地查找和打开项目中的文件,我们需要使用command-t插件。它有一些部分需要进行编译,所以将它放在子模块的目录中并没有完成安装。进入到你的~/.vim/bundle/command-t文件夹,然后运行“rake make”。这需要先把ruby安装好。默认情况下,command-t绑定到t。它可以使用模糊文本来查找项目中的任何文件。
It also supports searching only through opened buffers, instead of files using b.
使用b可以搜索所有打开的缓冲区而不是所有文件。

====文件浏览====
NERD Tree is a project file browser. I must admit I used this heavily back when I was migrating from Visual Studio and used to the Solution Explorer, but I rarely use it anymore. Command-T is usually all you'll need. It is useful when you are getting to know a new codebase for the first time though. Lets bind a shortcut key for opening it:
NERD Tree是一个项目文件浏览器。必须承认,曾经习惯了Visual Studio的Solution Explorer的时候我经常使用这个插件,但我现在几乎不用它了。通常你会需要command-T。当你第一次了解一个新的代码库时,这个插件很有用。让我们绑定一个打开它的快捷键:
1map
n :NERDTreeToggle


====重构和跳转====
Ropevim is also a great tool that will allow you to navigate around your code. It supports automatically inserting import statements, goto definition, refactoring, and code completion. You'll really want to read up on everything it does, but the two big things I use it for is to jump to function or class definitions quickly and to rename things (including all their references).
Ropevim也是一个伟大的代码导航工具。它支持自动插入import语句、转到定义、重构和代码完成。看到它,你可能会想了解它所支持的所有功能,但我主要用它来解决两个问题:快速跳转到函数或类的定义和重命名(包括所有的引用)。
For instance, if you are using django and you place your cursor over the class models.Model you reference and then called :RopeGotoDefintion, it would jump you straight to the django library to that class definition. We already have it installed in our bundles, so we bind it to a key to use it:
例如,如果您使用了Django,并把光标放在它的某个类名上。键入:RopeGotoDefintion,你就跳转到了Django库中那个类的定义处。我们已经安装在bundle中安装了它,所以我们把它绑定到一个快捷键上:
12map
j :RopeGotoDefinition
map
r :RopeRename

====搜索====
The final tool that really speeds up navigating your code is the Ack plugin. Ack is similar to grep, but much better in my opinion. You can fuzzy text search for anything in your code (variable name, class, method, etc) and it'll give you a list of files and line numbers where they are defined so you can quickly cycle through them. Just bind the searching to a key:
最后一个可以真正加快代码导航的工具是Ack插件。Ack类似于grep,但我认为它比grep好的多。你可以模糊搜索代码中任何东西(包括变量名、类、方法等),它会给你一个文件名和行号的列表,这样就可以很快地在结果中跳转。下面绑定搜索键:
1nmap
a :Ack!

We use ! at the end of it so it doesn't open the first result automatically.
我们在最后增加了一个!这样它就不会自动打开一个搜索结果。

Git集成


We installed 2 plugins, git.vim and fugitive, that give us all the integration we need. Git.vim will provide us syntax highlighting for git configuration files; fugitive provides a great interface for interacting with git including getting diffs, status updates, committing, and moving files.
两个插件完成了我们需要的所有功能:git.vim和fugitive。Git.vim插件提供了git配置文件的语法高亮功能,而fugitive使得我们可以方便地与git互动,包括获得版本差异、状态更新、提交和移动文件等。
Fugitive also allows you to view what branch you are working in directly from vim. Add this to your statusline in ~/.vimrc:
Fugitive还可以在vim中查看当前工作在哪个分支。将其添加到vim状态栏上,在~/.vimrc中添加:
1%{fugitive#statusline()}

The big commands you need to know:
你需要了解的常用命令:
Gblame: This allows you to view a line by line comparison of who the last person to touch that line of code is.
Gblame:逐行查看在上次更新以来的差异
Gwrite: This will stage your file for commit, basically doing git add
Gwrite:缓存文件,基本上就是执行git add <文件名>
Gread: This will basically run a git checkout
Gread: 运行git checkout <文件名>
Gcommit: This will just run git commit. Since its in a vim buffer, you can use keyword completion (Ctrl-N), like test_all to find the method name in your buffer and complete it for the commit message. You can also use + and - on the filenames in the message to stage/unstage them for the commit.
Gcommit: 运行git commit命令。由于这是在vim缓冲区中,你可以在commit消息中使用Ctrl+N来自动补全,如使用test_all来查找方法名。您可以在文件名前使用+或-来缓存或取消缓存。

测试集成


====Django nose====
Test runner integration really depends on the testing library you are using and what type of tests you are running but we included a great generic plugin called MakeGreen that executes off of vim's makeprg variable. So for instance, if you are using django with django-nose you could define a shortcut key in your ~/.vimrc like this:
测试集成严重依赖于测试库和测试类型,但一个伟大通用插件MakeGreen解决了这个问题,它执行vim的makeprg变量表示的测试命令。因此,如果是使用了diango-nose,你可以在~/.vimrc中这样定义一个快捷键:
1map
dt :
setmakeprg=python/
manage.py/
test/|:call
MakeGreen()

This will just give you a green bar at the bottom of vim if your test passed or a red bar with the message of the failed test if it doesn't. Very simple.
测试成功会在vim底部显示一个绿色条,而测试失败则显示红色条和失败的测试用例。使用非常简单。
====py.test====
I also included the py.test vim plugin for those who prefer it. This plugin has a lot more functionality including executing individual tests by class, file, or method. You can also cycle through the individual assertion errors. I have the following bindings:
我也为喜欢py.test的人增加了相应的插件。这个插件包含更多的功能,包括执行单独的按类、文件或方法测试。同上面一样,你也可以在每个断言错误处跳转。我作了以下的绑定:
12345678"
Execute the tests
nmap
tf :Pytest
filenmap
tc :Pytest class
nmap
tm :Pytest method
"
cycle through
testerrorsnmap
tn :Pytest next
nmap
tp :Pytest previous
nmap
te :Pytest error


====Virtualenv====
Vim doesn't realize that you are in a virtualenv so it wont give you code completion for libraries only installed there. Add the following script to your ~/.vimrc to fix it:
Vim不知道你在virtualenv环境中,所以它无法对仅在virtualenv中安装的库提供代码补全。在~/.vimrc中添加以下命令来修复这个问题:
1234567891011"
Add the virtualenv's site-packages to vim path
py
<< EOF
importos.pathimportsysimportvimif'VIRTUAL_ENV'inos.environ:project_base_dir
= os.environ[
'VIRTUAL_ENV']sys.path.insert(0,
project_base_dir)
activate_this
= os.path.
join(project_base_dir, 'bin/activate_this.py')execfile(activate_this,
dict(__file__=activate_this))
EOF

====Django====
The only true django tweak I make is before I open vim I'll export the DJANGO_SETTINGS_MODULE environment so that I get code completion for django modules as well:
对于Django,只需要在vim打开时导出DJANGO_SETTINGS_MODULE环境变量,就可以实现Django模块的代码补全:
1exportDJANGO_SETTINGS_MODULE=project.settings

分享给朋友:
您可能感兴趣的文章:
随机阅读: