1. 程式人生 > >Vim配置(python版)

Vim配置(python版)

its enter conf esc project ipy amp put 環境

由於馬上將用到django框架,需要有一個好的ide來coding,之前做C的開發時候體會到了vim的強大,所以編寫python也決定采用vim。

PS:除了vim,一般瀏覽代碼多用atom和sublime,具體可以自己google。

之前做C的項目時采用了spf13-vim,git地址:https://github.com/spf13/spf13-vim。喜歡的同學可以去下載。

這裏由於環境限制,準備配置一套新的簡單一些的vim。好久沒有配置了,這裏寫個文檔記錄下來,重新溫習一遍。

這裏推薦一大神的配置 http://sontek.net/blog/detail/turning-vim-into-a-modern-python-ide 這個地址如果訪問不了,看這裏:http://www.tuicool.com/articles/ZRv6Rv

我沒有采用這個配置 感覺配置太重 沒必要 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 [[email protected] 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‘

技術分享圖片

請看Vimcasts的這部視頻,了解更多情況。

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代碼,選擇第二種即可。

技術分享圖片

效果圖:

技術分享圖片

Vim配置(python版)