VIM配置Python环境

VIM配置Python环境


参考:
- https://realpython.com/blog/python/vim-and-python-a-match-made-in-heaven/
- https://segmentfault.com/a/1190000003962806
- https://linux.cn/article-3314-1.html


1.查看vim版本

vim --version

可以查看到anaconda下vim具体的版本及其信息:

(pytorch) ggy@GPU4:~$ vim --version
VIM - Vi IMproved 7.4 (2013 Aug 10, compiled Nov 24 2016 16:44:48)
Included patches: 1-1689
Extra patches: 8.0.0056
Modified by pkg-vim-maintainers@lists.alioth.debian.org
Compiled by pkg-vim-maintainers@lists.alioth.debian.org
Huge version without GUI.  Features included (+) or not (-):
+acl             +farsi           +mouse_netterm   +tag_binary
+arabic          +file_in_path    +mouse_sgr       +tag_old_static
+autocmd         +find_in_path    -mouse_sysmouse  -tag_any_white
-balloon_eval    +float           +mouse_urxvt     -tcl
-browse          +folding         +mouse_xterm     +terminfo
++builtin_terms  -footer          +multi_byte      +termresponse
+byte_offset     +fork()          +multi_lang      +textobjects
+channel         +gettext         -mzscheme        +timers
+cindent         -hangul_input    +netbeans_intg   +title
-clientserver    +iconv           +packages        -toolbar
-clipboard       +insert_expand   +path_extra      +user_commands
+cmdline_compl   +job             -perl            +vertsplit
+cmdline_hist    +jumplist        +persistent_undo +virtualedit
+cmdline_info    +keymap          +postscript      +visual
+comments        +langmap         +printer         +visualextra
+conceal         +libcall         +profile         +viminfo
+cryptv          +linebreak       -python          +vreplace
+cscope          +lispindent      +python3         +wildignore
+cursorbind      +listcmds        +quickfix        +wildmenu
+cursorshape     +localmap        +reltime         +windows
+dialog_con      -lua             +rightleft       +writebackup
+diff            +menu            -ruby            -X11
+digraphs        +mksession       +scrollbind      -xfontset
-dnd             +modify_fname    +signs           -xim
-ebcdic          +mouse           +smartindent     -xsmp
+emacs_tags      -mouseshape      +startuptime     -xterm_clipboard
+eval            +mouse_dec       +statusline      -xterm_save
+ex_extra        +mouse_gpm       -sun_workshop    -xpm
+extra_search    -mouse_jsbterm   +syntax
   system vimrc file: "$VIM/vimrc"
     user vimrc file: "$HOME/.vimrc"
 2nd user vimrc file: "~/.vim/vimrc"
      user exrc file: "$HOME/.exrc"
  fall-back for $VIM: "/usr/share/vim"
Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H   -Wdate-time  -g -O2 -fPIE -fstack-protector-strong -Wformat -Werror=format-security -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1
Linking: gcc   -Wl,-Bsymbolic-functions -fPIE -pie -Wl,-z,relro -Wl,-z,now -Wl,--as-needed -o vim        -lm -ltinfo -lnsl  -lselinux  -lacl -lattr -lgpm -ldl     -L/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu -lpython3.5m -lpthread -ldl -lutil -lm
需要确保两点:
  1. vim版本大于7.3
  2. Features included 中需要看到 +python
2.安装Vundle

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

3. 配置.vimrc文件
(1). 首先在自己的目录下新建一个.vimrc文件

touch ~/.vimrc

(2). 在.vimrc文件设置Vundle

gedit ~/.vimrc

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
Plugin 'gmarik/Vundle.vim'

" 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

设置完成后打开vim,运行:

:PluginInstall++

3.设置IDE
分割界面

gedit ~/.vimrc

加入

set splitbelow
set splitright

将下面和右边的分割,分割后面的界面更类似与图形化IDE

.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 切换到左面
代码折叠
" Enable folding
set foldmethod=indent
set foldlevel=99

设置快捷键,使用za折叠和展开

" Enable folding with the spacebar
nnoremap <space> za

设置插件:
Plugin 'tmhedberg/SimpylFold'
在vim中运行::PluginInstall

如果想显示折叠代码,加入
let g:SimpylFold_docstring_preview=1

python 缩进

代码折叠是基于缩进的,需要进行一下设置
- 设置python代码按照PEP8 标准进行缩进

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

textwidth不要超过80

可以同时设置一下其他的文件格式

au BufNewFile,BufRead *.js,*.html,*.css
    \ set tabstop=2 |
    \ set softtabstop=2 |
    \ set shiftwidth=2 |
  • 自动缩进
    使用 indentpython.vim 插件实现自动缩进。
    Plugin 'vim-scripts/indentpython.vim'

不要忘记执行:PluginInstall

检测不必要的空格

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

加入UTF8格式支持

set encoding=utf-8

自动补齐

最好的Python自动补齐的插件是 YouCompleteMe
Bundle 'Valloric/YouCompleteMe'

使用YouCompleteMe**需要一些C语言的库支持**,官方网站有非常详细的介绍,在这里不在重复

加入一些个性化设置,:

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

前一行确保自动填充窗口在完成时消失,而后者设置一个跳转定义的快捷方式space-g

支持虚拟环境

上面“转到定义”功能的一个问题,就是默认情况下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

这一步可能报错:

line   63:
E319: Sorry, the command is not available in this version: py << EOF
line   64:
E492: Not an editor command: import os
line   65:
E492: Not an editor command: import sys
line   66:
E15: Invalid expression: 'VIRTUAL_ENV' in os.environ:
line  117:
E171: Missing :endif

解决方案sudo apt install vim-nox-py2

语法检查/高亮显示

使用 syntastic插件检查语法:

Plugin 'vim-syntastic/syntastic'

PEP8 检查插件:

Plugin 'nvie/vim-flake8'

高亮显示

let python_highlight_all=1
syntax on
配色方案
Plugin 'jnurmine/Zenburn'
Plugin 'altercation/vim-colors-solarized'

根据VIM的模式设置主题

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

设置F5切换日间和夜间模式:
call togglebg#map("<F5>")

文件浏览

文件树形结构
Plugin 'scrooloose/nerdtree'

tab键

Plugin 'jistr/vim-nerdtree-tabs'

隐藏.pyc文件:

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

超级搜索

在Vim中搜索任何文件

Plugin 'kien/ctrlp.vim'

正如插件名,按Ctrl+P就可以进行搜索。

显示行号

set nu

Git集成

在Vim中执行基本的Git命令

Plugin 'tpope/vim-fugitive'

状态栏

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

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

系统剪贴板

set clipboard=unnamed

编辑~/.inputrcShell开启Vim编辑模式

gedit ~/.inputrc
加入
set editing-mode vi

最后,不要忘记执行:PluginInstall

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值