[转]Linux下的Python版vim配置

5,161次阅读
一条评论

共计 10938 个字符,预计需要花费 28 分钟才能阅读完成。

哈哈,俺属于Linux小白用户,现正在摸索阶段,想使用Linux下的vim编辑器作为Python的代码编辑工具,但是vim本身配置较为简单,针对Python语法需要做一些配置,于是在网上转了一片我认为较好的配置,贴出来给大家作为参考哦~

_________________________华丽的分割线______________________________________________

1、安装

vim –version 查看vim版本

在这一步,你要确保已经满足以下两点要求:

  1. Vim编辑版本应该大于7.3。
  2. 支持Python语言。在所选编辑器的功能中,确保你看到了+python

然后 yum update;yum install -y vim

2、验证安装

确保你已经安装了7.3版本以上、支持Python的Vim编辑器。你可以再次运行vim --version进行确认。如果你想知道Vim中使用的Python版本,你可以在编辑器中运行:python import sys; print(sys.version)

1
2
3
4
5
[root@server-15 steth]# python
Python 2.7.5 (default, Sep 15 2016, 22:37:39)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

这行命令会输出你的编辑器当前的Python版本。如果报错,那么你的编辑器就不支持Python语言,需要重装或重新编译。

Vim编辑器安装完成后,我们来看看如何将其设置为Python开发的强大环境。

3、Vundle

Vim有多个扩展管理器,但是我们强烈推荐Vundle。你可以把它想象成Vim的pip。有了Vundle,安装和更新包这种事情不费吹灰之力。

我们现在来安装Vundle:

git clone https://github.com/gmarik/Vundle.vim.git ~/.vim/bundle/Vundle.vim

该命令将下载Vundle插件管理器,并将它放置在你的Vim编辑器bundles文件夹中。现在,你可以通过.vimrc配置文件来管理所有扩展了。

将配置文件添加到你的用户的home文件夹中:

touch ~/.vimrc

接下来,把下来的Vundle配置添加到配置文件的顶部:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
set nocompatible              " required
filetype off                  " required
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')
" let Vundle manage Vundle, required
<strong>Plugin 'gmarik/Vundle.vim'</strong>
" Add all your plugins here (note older versions of Vundle used Bundle instead of Plugin)
" All of your Plugins must be added before the following line
call vundle#end()            " required
filetype plugin indent on    " required

这样,你就完成了使用Vundle前的设置。之后,你就可以在配置文件中添加希望安装的插件,然后打开Vim编辑器,运行下面的命令:

:PluginInstall

这个命令告诉Vundle施展它的魔法——自动下载所有的插件,并为你进行安装和更新。

 

之后 如果想要安装其他新的插件 就按照这个格式写入.vimrc配置文件即可。(注意.vimrc文件必须放在~目录下才会被识别)

4、vimrc配置

提供一套我的暂时的配置:

1 "vundle
  2 set nocompatible
  3 filetype off
  4 
  5 set rtp+=~/.vim/bundle/Vundle.vim
  6 call vundle#begin()
  7 
  8 Plugin 'VundleVim/Vundle.vim'
  9 "git interface
 10 Plugin 'tpope/vim-fugitive'
 11 "filesystem
 12 Plugin 'scrooloose/nerdtree'
 13 Plugin 'jistr/vim-nerdtree-tabs'
 14 Plugin 'kien/ctrlp.vim' 
 15 
 16 "html
 17 "  isnowfy only compatible with python not python3
 18 Plugin 'isnowfy/python-vim-instant-markdown'
 19 Plugin 'jtratner/vim-flavored-markdown'
 20 Plugin 'suan/vim-instant-markdown'
 21 Plugin 'nelstrom/vim-markdown-preview'
 22 "python sytax checker
 23 Plugin 'nvie/vim-flake8'
 24 Plugin 'vim-scripts/Pydiction'
 25 Plugin 'vim-scripts/indentpython.vim'
 26 Plugin 'scrooloose/syntastic'
 27 
 28 "auto-completion stuff
 29 "Plugin 'klen/python-mode'
 30 Plugin 'Valloric/YouCompleteMe'
 31 Plugin 'klen/rope-vim'
 32 "Plugin 'davidhalter/jedi-vim'
 33 Plugin 'ervandew/supertab'
 34 ""code folding
 35 Plugin 'tmhedberg/SimpylFold'
 36 
 37 "Colors!!!
 38 Plugin 'altercation/vim-colors-solarized'
 39 Plugin 'jnurmine/Zenburn'
 40 
 41 call vundle#end()
 42 
 43 filetype plugin indent on    " enables filetype detection
 44 let g:SimpylFold_docstring_preview = 1
 45 
 46 "autocomplete
 47 let g:ycm_autoclose_preview_window_after_completion=1
 48 
 49 "custom keys
 50 let mapleader=" "
 51 map <leader>g  :YcmCompleter GoToDefinitionElseDeclaration<CR>
 52 "
 53 call togglebg#map("<F5>")
 54 "colorscheme zenburn
 55 "set guifont=Monaco:h14
 56 
 57 let NERDTreeIgnore=['\.pyc', '\~'] "ignore files in NERDTree
 58 
 59 "I don't like swap files
 60 set noswapfile
 61 
 62 "turn on numbering
 63 set nu
 64 
 65 "python with virtualenv support
 66 py << EOF
 67 import os.path
 68 import sys
 69 import vim
 70 if 'VIRTUA_ENV' in os.environ:
 71   project_base_dir = os.environ['VIRTUAL_ENV']
 72   sys.path.insert(0, project_base_dir)
 73   activate_this = os.path.join(project_base_dir,'bin/activate_this.py')
 74   execfile(activate_this, dict(__file__=activate_this))
 75 EOF
 76 
 77 "it would be nice to set tag files by the active virtualenv here
 78 ":set tags=~/mytags "tags for ctags and taglist
 79 "omnicomplete
 80 autocmd FileType python set omnifunc=pythoncomplete#Complete
 81 
 82 "------------Start Python PEP 8 stuff----------------
 83 " Number of spaces that a pre-existing tab is equal to.
 84 au BufRead,BufNewFile *py,*pyw,*.c,*.h set tabstop=4
 85 
 86 "spaces for indents
 87 au BufRead,BufNewFile *.py,*pyw set shiftwidth=4
 88 au BufRead,BufNewFile *.py,*.pyw set expandtab
 89 au BufRead,BufNewFile *.py set softtabstop=4
 90 
 91 " Use the below highlight group when displaying bad whitespace is desired.
 92 highlight BadWhitespace ctermbg=red guibg=red
 93 
 94 " Display tabs at the beginning of a line in Python mode as bad.
 95 au BufRead,BufNewFile *.py,*.pyw match BadWhitespace /^\t\+/
 96 " Make trailing whitespace be flagged as bad.
 97 au BufRead,BufNewFile *.py,*.pyw,*.c,*.h match BadWhitespace /\s\+$/
 98 
 99 " Wrap text after a certain number of characters
100 au BufRead,BufNewFile *.py,*.pyw, set textwidth=100
101 
102 " Use UNIX (\n) line endings.
103 au BufNewFile *.py,*.pyw,*.c,*.h set fileformat=unix
104 
105 " Set the default file encoding to UTF-8:
106 set encoding=utf-8
107 
108 " For full syntax highlighting:
109 let python_highlight_all=1
110 syntax on
111 
112 " Keep indentation level from previous line:
113 autocmd FileType python set autoindent
114 
115 " make backspaces more powerfull
116 set backspace=indent,eol,start
117 
118 
119 "Folding based on indentation:
120 autocmd FileType python set foldmethod=indent
121 "use space to open folds
122 nnoremap <space> za 
123 "----------Stop python PEP 8 stuff--------------
124 
125 "js stuff"
126 autocmd FileType javascript setlocal shiftwidth=2 tabstop=2

5、配置讲解

使用:sv <filename>命令打开一个文件,你可以纵向分割布局(新文件会在当前文件下方界面打开),使用相反的命令:vs <filename>, 你可以得到横向分割布局(新文件会在当前文件右侧界面打开)。

你还可以嵌套分割布局,所以你可以在分割布局内容再进行分割,纵向或横向都可以,直到你满意为止。众所周知,我们开发时经常需要同时查看多个文件。

贴士:记得在输入完:sv后,利用tab补全功能,快速查找文件。

贴士:你还可以指定屏幕上可以进行分割布局的区域,只要在.vimrc文件中添加下面的代码即可:

set splitbelow
set splitright

贴士:想要不使用鼠标就切换分割布局吗?只要将下面的代码添加到.vimrc文件中,你就可以通过快捷组合键进行切换。

"split navigations
nnoremap <C-J> <C-W><C-J>
nnoremap <C-K> <C-W><C-K>
nnoremap <C-L> <C-W><C-L>
nnoremap <C-H> <C-W><C-H>

组合快捷键:

  • Ctrl-j 切换到下方的分割窗口
  • Ctrl-k 切换到上方的分割窗口
  • Ctrl-l 切换到右侧的分割窗口
  • Ctrl-h 切换到左侧的分割窗口

换句话说, 按Ctrl+Vim的标准移动键,就可以切换到指定窗口。

nnoremap是什么意思?——简单来说,nnoremap将一个组合快捷键映射为另一个快捷键。一开始的n,指的是在Vim的正常模式(Normal Mode)下,而不是可视模式下重新映射。基本上,nnoremap <C-J> <C-W><C-j>就是说,当我在正常模式按下<C-J>时,进行<C-W><C-j>操作。更多信息请看这里

缓冲区(Buffers)

虽然Vim支持tab操作,仍有很多人更喜欢缓冲区和分割布局。你可以把缓冲区想象成最近打开的一个文件。Vim提供了方便访问近期缓冲区的方式,只需要输入:b <buffer name or number>,就可以切换到一个已经开启的缓冲区(此处也可使用自动补全功能)。你还可以通过ls命令查看所有的缓冲区。

专业贴士: 在:ls命令输出的最后,Vim会提示“敲击Enter继续查看”,这时你可以直接输入:b <buffer name>,立即选择缓冲区。这样可以省掉一个按键操作,也不必去记忆缓冲区的名字。

代码折叠(Code Folding)

大多数“现代”集成开发环境(IDE)都提供对方法(methods)或类(classes)进行折叠的手段,只显示类或方法的定义部分,而不是全部的代码。

你可以在.vimrc中添加下面的代码开启该功能:

" Enable folding
set foldmethod=indent
set foldlevel=99

这样就可以实现,但是你必须手动输入za来折叠(和取消折叠)。使用空格键会是更好的选择。所以在你的配置文件中加上这一行命令吧:

" Enable folding with the spacebar
nnoremap <space> za

现在你可以轻松地隐藏掉那些当前工作时不需要关注的代码了。

第一个命令,set foldmethod=ident会根据每行的缩进开启折叠。但是这样做会出现超过你所希望的折叠数目。但是别怕,有几个扩展就是专门解决这个问题的。在这里,我们推荐SimplyFold。在.vimrc中加入下面这行代码,通过Vundle进行安装:

Plugin 'tmhedberg/SimpylFold'

不要忘记执行安装命令::PluginInstall

专业贴士: 希望看到折叠代码的文档字符串?

let g:SimpylFold_docstring_preview=1

Python代码缩进

当然,想要代码折叠功能根据缩进情况正常工作,那么你就会希望自己的缩进是正确的。这里,Vim的自带功能无法满足,因为它实现不了定义函数之后的自动缩进。我们希望Vim中的缩进能做到以下两点:

  • 首先,缩进要符合PEP8标准。
  • 其次,更好地处理自动缩进。

PEP8

要支持PEP8风格的缩进,请在.vimrc文件中添加下面的代码:

au BufNewFile,BufRead *.py
\ set tabstop=4
\ set softtabstop=4
\ set shiftwidth=4
\ set textwidth=79
\ set expandtab
\ set autoindent
\ set fileformat=unix

这些设置将让Vim中的Tab键就相当于4个标准的空格符,确保每行代码长度不超过80个字符,并且会以unix格式储存文件,避免在推送到Github或分享给其他用户时出现文件转换问题。

另外,对于全栈开发,你可以设置针对每种文件类型设置au命令:

au BufNewFile,BufRead *.js, *.html, *.css
\ set tabstop=2
\ set softtabstop=2
\ set shiftwidth=2

自动缩进

自动缩进有用,但是在某些情况下(比如函数定义有多行的时候),并不总是会达到你想要的效果,尤其是在符合PEP8标准方面。我们可以利用indentpython.vim插件,来解决这个问题:

Plugin 'vim-scripts/indentpython.vim'

标示不必要的空白字符

我们希望避免出现多余的空白字符。可以让Vim帮我们标示出来,使其很容易发现并删除。

au BufRead,BufNewFile *.py,*.pyw,*.c,*.h match BadWhitespace /\s\+$/

这会将多余的空白字符标示出来,很可能会将它们变成红色突出。

支持UTF-8编码

大部分情况下,进行Python开发时你应该使用UTF-8编码,尤其是使用Python 3的时候。确保Vim设置文件中有下面的命令:

set encoding=utf-8

自动补全

支持Python自动补全的最好插件是YouCompleteMe。我们再次使用Vundle安装:

Plugin 'Valloric/YouCompleteMe'

安装会在下一章说明。

安装完成后,插件自带的设置效果就很好,但是我们还可以进行一些小的调整:

let g:ycm_autoclose_preview_window_after_completion=1
map <leader>g  :YcmCompleter GoToDefinitionElseDeclaration<CR>

上面的第一行确保了在你完成操作之后,自动补全窗口不会消失,第二行则定义了“转到定义”的快捷方式。

支持Virtualenv虚拟环境

上面“转到定义”功能的一个问题,就是默认情况下Vim不知道virtualenv虚拟环境的情况,所以你必须在配置文件中添加下面的代码,使得Vim和YouCompleteMe能够发现你的虚拟环境:

"python with virtualenv support
py << EOF
import os
import sys
if 'VIRTUAL_ENV' in os.environ:
  project_base_dir = os.environ['VIRTUAL_ENV']
  activate_this = os.path.join(project_base_dir, 'bin/activate_this.py')
  execfile(activate_this, dict(__file__=activate_this))
EOF

这段代码会判断你目前是否在虚拟环境中编辑,然后切换到相应的虚拟环境,并设置好你的系统路径,确保YouCompleteMe能够找到相应的site packages文件夹。

语法检查/高亮

通过安装syntastic插件,每次保存文件时Vim都会检查代码的语法:

Plugin 'scrooloose/syntastic'

还可以通过这个小巧的插件,添加PEP8代码风格检查:

Plugin 'nvie/vim-flake8'

最后,让你的代码变得更漂亮:

let python_highlight_all=1
syntax on

配色方案

配色方案可以和你正在使用的基础配色共同使用。GUI模式可以尝试solarized方案, 终端模式可以尝试Zenburn方案

Plugin 'jnurmine/Zenburn'
Plugin 'altercation/vim-colors-solarized'

接下来,只需要添加一点逻辑判断,确定什么模式下使用何种方案就可以了:


if has('gui_running')
  set background=dark
  colorscheme solarized
else
  colorscheme Zenburn
endif

Solarized方案同时提供了暗色调和轻色调两种主题。要支持切换主题功能(按F5)也非常简单,只需添加:

call togglebg#map("<F5>")

文件浏览

如果你想要一个不错的文件树形结构,那么NERDTree是不二之选。

Plugin 'scrooloose/nerdtree'

如果你想用tab键,可以利用vim-nerdtree-tabs插件实现:


Plugin 'jistr/vim-nerdtree-tabs'

还想隐藏.pyc文件?那么再添加下面这行代码吧:

let NERDTreeIgnore=['\.pyc$', '\~$'] "ignore files in NERDTree

超级搜索

想要在Vim中搜索任何文件?试试ctrlP插件吧:

Plugin 'kien/ctrlp.vim'

正如插件名,按Ctrl+P就可以进行搜索。如果你的检索词与想要查找的文件相匹配的话,这个插件就会帮你找到它。哦,对了——它不仅仅可以搜索文件,还能检索标签!更多信息,可以观看这个Youtube视频.

显示行号

开启显示行号:

set nu

Git集成

想要在Vim中执行基本的Git命令?vim-fugitive插件则是不二之选。

Plugin 'tpope/vim-fugitive'

Powerline状态栏

Powerline是一个状态栏插件,可以显示当前的虚拟环境、Git分支、正在编辑的文件等信息。

这个插件是用Python编写的,支持诸如zsh、bash、tmux和IPython等多种环境。

Plugin 'Lokaltog/powerline', {'rtp': 'powerline/bindings/vim/'}

请查阅插件的官方文档,了解配置选项。

系统剪贴板

通常Vim会忽视系统剪贴板,而使用自带的剪贴板。但是有时候你想从Vim之外的程序中剪切、复制、粘贴文本。在OS X平台上,你可以通过这行代码访问你的系统剪贴板:

set clipboard=unnamed

Shell开启Vim编辑模式

最后,当你熟练掌握了Vim和它的键盘快捷方式之后,你会发现自己经常因为shell中缺乏相同的快捷键而懊恼。没关系,大部分的shell程序都有Vi模式。在当前shell中开启Vi模式,你只需要在~/.inputrc文件中添加这行代码:

set editing-mode vi

现在,你不仅可以在shell中使用Vim组合快捷键,还可以在Python解释器以及任何利用GNU Readline程序的工具(例如,大多数的数据库shell)中使用。现在,你在什么地方都可以使用Vim啦!

 

6、YouCompleteMe

youcompleteme安装比较特殊,需要编译才能用。

官网的文档链接在这里:https://github.com/Valloric/YouCompleteMe

编译之前,首先要安装plugin  根据我的配置,这时plugin已经都安装完毕(YouCompleteMe安装时间比较长,请耐心等待)

安装完后,进入YoucompleteMe目录,

#cd ~/.vim/bundle/YoucompleteMe

#./install –clang-completer   //PS这里可以使用install –help查看支持哪些补全

#cp third_party/ycmd/examples/.ycm_extra_conf.py ~/

即可

好了,可以直接体验了。当然以前的cscope以及ctags实际上还是有用的,在看linux内核的时候还是比较依赖这些标签库。

YoucompleteMe的好处是智能分析,不像以前的ctags靠字母乱猜。

 

注意:可能编译会报错,很有可能是你的依赖包没有装完,请确定安装所有依赖包,确定vim的版本python版本:Make sure you have Vim 7.3.598 with Python 2 or Python 3 support

 Install development tools and CMake: sudo yum install automake gcc gcc-c++ kernel-devel cmake(这是官网提供的依赖)

Make sure you have Python headers installed: sudo dnf install python-devel python3-devel.(python开发包)

Compiling YCM with semantic support for C-family languages:

cd ~/.vim/bundle/YouCompleteMe
./install.py --clang-completer

Compiling YCM without semantic support for C-family languages:

cd ~/.vim/bundle/YouCompleteMe
./install.py

The following additional language support options are available:

    C# support: install Mono and add --omnisharp-completer when calling ./install.py.
    Go support: install Go and add --gocode-completer when calling ./install.py.
    TypeScript support: install Node.js and npm then install the TypeScript SDK with npm install -g typescript.
    JavaScript support: install Node.js and npm and add --tern-completer when calling ./install.py.
    Rust support: install Rust and add --racer-completer when calling ./install.py.


这是编译选项,支持各种语言的补齐,如果只需要开发python代码,选择第二种即可。
正文完
请博主喝杯咖啡吧!
post-qrcode
 
admin
版权声明:本站原创文章,由 admin 2016-11-26发表,共计10938字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(一条评论)
验证码
admin 博主
2016-11-26 12:59:14 回复

给洋洋洋赞一个

 Android  Chrome  中国广东省深圳市联通