12.21 golang實戰-1:搭建vim-go開發環境

目錄

(1).基本概念與注意事項

(2).升級vim8

(3).Vundle安裝

a.下載Vundle

b.插件配置

c.文件解析

d.安裝Vundle插件

(4).配置高亮

(5).安裝YouCompleteMe'插件

(6).安裝go插件

1.安裝go環境

2.安裝vim-go插件

3.修改go.vim

(7).安裝樹形目錄插件

(8).vim常用命令


(1).基本概念


Vundle: 管理vim插件

YouCompleteMe: 自動補齊插件


本文實操環境:

LSB Version: :core-4.1-amd64:core-4.1-noarch

Distributor ID: CentOS

Description: CentOS Linux release 7.3.1611 (Core)

Release: 7.3.1611

Codename: Core


整個環境很難裝,會遇到很多問題,不同os不同基礎組件版本的不同都會帶來各種各樣的問題,本文僅保證上述OS下的順利部署(其實你可能還會遇到一些問題);其他版本下的安裝大同小異,但是會出現各種各樣問題。


Python版本:3.6.8,pthon3的版本差異也會導致出現問題;

YouCompleteMe版本:master最新;

Vim版本:8.1-2171

go版本:version go1.13.3 linux/amd64


完成安裝後最好使用xshell進行開發,SecureCRT下開發go有可能出現亂碼(即使你把所有相關編碼都改成UTF8)。


(2) .升級vim8


不升級有可能報版本問題:

YouCompleteMe unavailable: requires Vim 7.4.1578+。

vim-go requires at least Vim 8.0.1453 or Neovim 0.3.2, but you're using an older version。

而且很多插件現在對vim7支持不一定好(也可以理解)。

升級到vim的最新版本。


注意不要使用python3.8等最新版本(我採坑了,手賤),python特麼又要變API,vim目前還不支持新版本的python,我使用3.6.8。


1.安裝依賴


yum install -y cmake gcc-c++ make ncurses-devel wget libzip bzip2 git zlib-devel


zlib-devel作用:

如果不安裝,編譯python3.6.8時會報錯:

zipimport.ZipImportError: can't decompress data; zlib not available


安裝python3.6.8:

https://www.python.org/downloads/release/python-368/

wget https://www.python.org/ftp/python/3.6.8/Python-3.6.8.tar.xz

解壓:tar -xvf Python-3.6.8.tar.xz

建立空文件夾,放置python安裝程序: mkdir /usr/local/python3

執行: ./configure prefix=/usr/local/python3 --enable-shared --with-openssl=/usr/local/ssl

執行: make && make install

建立軟連接:將python3都指向python3.6.8

ln -s /usr/local/python3/bin/python3.6 /usr/local/bin/python3

ln -s /usr/local/python3/bin/pip3.6 /usr/bin/pip3

升級python3後有可能yum不能使用,因為yum默認使用python2,需要修改/usr/bin/yum,第一行改為:#!/usr/bin/python2.x


執行python3時有可能報錯:

error while loading shared libraries: libpython3.6m.so.1.0: cannot open shared object file: No such file or directory

需要拷貝源文件:

cp libpython3.6m.so.1.0 /usr/lib64

再執行python3則OK。


注意:

1. YouCompleteMe,需要python3,以動態連接庫的方式去編譯,即python3在編譯的時候需要加上:--enable-shared,同時在python3.6.5之後在使用pip的時候,需要ssl,所以也需要指定:--with-openssl=/usr/local/ssl,/usr/local/ssl是openssl的安裝路徑,同時python3,需要openssl的版本在1.0.2或是1.1.1之上,所以有可能需要升級系統的

2. 因為後續還要安裝YouCompleteMe插件,YCM插件需要vim支持python2,所以這裡python2和python3都有配置。試過只配置python3不配置python2支持會導致插件安裝成功後打開.py文件vim就會報錯: Vim: Caught deadly signal SEGV Segmentation fault。

3. 指定正確的路徑很重要。如果您使用的是Python,則您的config目錄可能具有特定於計算機的名稱(例如config-3.6m-x86_64-linux-gnu),找到自己的config路徑並相應的更改configure裡的python路徑


2.安裝vim8


安裝依賴:yum -y install python-devel


wget https://github.com/vim/vim/archive/v8.1.2171.tar.gz

解壓後進入目錄:

make clean


為了避免YouCompleteMed的最終錯誤:

unavailable: /usr/local/python3/lib/python3.6/lib-dynload/_socket.cpython-3。6m-x86_64-linux-gnu.so: undefined symbol: PyExc_OSError

需要加編譯參數:

--with-python3-config-dir=/usr/local/python3/lib/python3.6/config-3.6m-x86_64-linux-gnu


python2,python3都支持

./configure -enable-pythoninterp --with-python-command=/usr/bin/python --with-python-config-dir=/usr/lib64/python2.7/config --enable-python3interp=yes --with-python3-command=/usr/local/bin/python3 --with-python3-config-dir=/usr/local/python3/lib/python3.6/config-3.6m-x86_64-linux-gnu --with-features=huge --enable-fail-if-missing --enable-cscope --enable-multibyte --enable-fontset --prefix=/usr/local/vim8


make

make install


如果安裝時出現錯誤,使用make distclean清除。


rm /usr/bin/vim

ln -s /usr/local/vim8/bin/vim /usr/bin/vim


完成升級,執行vim --version驗證:

golang實戰-1:搭建vim-go開發環境


(3).Vundle安裝


參考官方:https://github.com/VundleVim/Vundle.vim#about


a.下載Vundle


將Vundle下載到本地,後面下載的插件也將會下載到~/.vim/bundle路徑下。

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


b.插件配置


將如下的內容粘貼到~/.vimrc的頂部,前提是,你本身.vimrc裡一開始沒有什麼其他內容。如果文件有內容,需要根據自身情況修改。


set nocompatible " be iMproved, 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 'VundleVim/Vundle.vim'


" The following are examples of different formats supported.

" Keep Plugin commands between vundle#begin/end.

" plugin on GitHub repo

" Plugin 'tpope/vim-fugitive'

" plugin from http://vim-scripts.org/vim/scripts.html

" Plugin 'L9'

" Git plugin not hosted on GitHub

" Plugin 'git://git.wincent.com/command-t.git'

" git repos on your local machine (i.e. when working on your own plugin)

" Plugin 'file:///home/gmarik/path/to/plugin'

" The sparkup vim>

" Pass the path to set the runtimepath properly.

" Plugin 'rstacruz/sparkup', {'rtp': 'vim/'}

" Install L9 and avoid a Naming conflict if you've already installed a

" different version somewhere else.

" Plugin 'ascenator/L9', {'name': 'newL9'}


" All of your Plugins must be added before the following line

call vundle#end() " required

filetype plugin indent on " required

" To ignore plugin indent changes, instead use:

"filetype plugin on

" Brief help

" :PluginList - lists configured plugins

" :PluginInstall - installs plugins; append `!` to update or just :PluginUpdate

" :PluginSearch foo - searches for foo; append `!` to refresh local cache

" :PluginClean - confirms removal of unused plugins; append `!` to auto-approve removal

" see :h vundle for more details or wiki for FAQ

" Put your non-Plugin stuff after this line


如果.vimrc不存在,將上述段落拷貝後可能由於編碼報錯,需要如下處理:

yum install -y dos2unix

dos2unix ~/.vimrc


c.文件解析


c.1.set nocompatible作用


set compatible 就是讓 vim 關閉所有擴展的功能,儘量模擬 vi 的行為。

但這樣就不應用 vim 的很多強大功能,所以一般沒有什麼特殊需要的話(比如執行很老的 vi 腳本),都要在 vim 的配置開始,寫上 set nocompatible,關閉兼容模式。由於這個選項是最最基礎的選項,會連帶很多其它選項發生變動(稱作副作用),所以它必需是第一個設定的選項。


c.2.filetype off作用


執行:filetype可以查看Vim的文件類型檢測功能是否已打開,默認你會看到:detection:ON plugin:OFF indent:OFF。


detection:默認情況vim會對文件自動檢測文件類型,也就是你看到的'detection:ON',同樣你可以手動關閉:filetype off。 可以用:set filetype查看當前文件是什麼類型了。 類似file.txt文件的filetype設置為python,那麼就和普通的python文件一樣的顯示效果了:set filetype=python。

另一種方式就是在文件內容中指定,Vim會從文件的頭幾行自動掃描文件是否有聲明文件的類型的代碼,如在文件的行首加入# vim: filetype=python,Java文件變通的做法/* vim: filetype=java */,總之就是把這行當作註釋,以致於不影響文件的編譯,這樣Vim不通過文件名也能檢測出文件是什麼類型了。


plugin:如果plugin狀態時ON,那麼就會在Vim的運行時環境目錄下加載該類型相關的插件。比如為了讓Vim更好的支持Python編程,你就需要下載一些Python相關的插件,此時就必須設置plugin為ON插件才會生效,具體設置方法就是:filetype plugin on


indent:不同類型文件有不同的方式,比如Python就要求使用4個空格作為縮進,而c使用兩個tab作為縮進,那麼indent就可以為不同文件類型選擇合適的縮進方式了。你可以在Vim的安裝目錄的indent目錄下看到定義了很多縮進相關的腳本。具體設置方法:filetype indent on。


以上三個參數,可以寫成一行filetype plugin indent on設置在_vimrc文件中。


c.3.set rtp+=~/.vim/bundle/Vundle.vim作用:


設置包括vundle和初始化相關的runtime path


c.4.call vundle#begin()與call vundle#end()作用


安裝的Plugin都在兩者之間配置。


d.安裝Vundle插件


執行vim命令,然後輸入::PluginInstall


golang實戰-1:搭建vim-go開發環境


(4).配置高亮


vim在粘貼內容的時候,如果遇到以#開始的註釋行,會自動將後續的所有行進行註釋。

取消這個功能也很簡單,只需要在根目錄下編輯.vimrc文件(如果沒有,就創建該文件),在其中添加下面的內容:

set paste


將如下內容複製到文件末尾:~/.vimrc


"ctags

set tags=tags;/


set wrapscan "啟用循環查找方式

set guifont=Monaco:h10 " 字體 && 字號

set expandtab " 設置tab鍵換空格

set tabstop=4 " 設置tab鍵的寬度

set shiftwidth=4 " 換行時行間交錯使用4個空格

set autoindent " 自動對齊

set backspace=2 " 設置退格鍵可用

set cindent shiftwidth=4 " 自動縮進4空格

set smartindent " 智能自動縮進

set ai! " 設置自動縮進

"set nu! " 顯示行號

"set showmatch " 顯示括號配對情況

"set mouse=a " 啟用鼠標

"set ruler " 右下角顯示光標位置的狀態行

set incsearch " 查找book時,當輸入/b時會自動找到

set hlsearch " 開啟高亮顯示結果

set incsearch " 開啟實時搜索功能

set nowrapscan " 搜索到文件兩端時不重新搜索

set nocompatible " 關閉兼容模式

set vb t_vb= " 關閉提示音

"set cursorline " 突出顯示當前行

set hidden " 允許在有未保存的修改時切換緩衝區


syntax enable " 打開語法高亮

syntax on " 開啟文件類型偵測

filetype indent on " 針對不同的文件類型採用不同的縮進格式

filetype plugin on " 針對不同的文件類型加載對應的插件

filetype plugin indent on " 啟用自動補全


set writebackup " 設置無備份文件

set nobackup

"set autochdir " 設定文件瀏覽器目錄為當前目錄

"set nowrap " 設置不自動換行

"set foldmethod=syntax " 選擇代碼摺疊類型

"set foldlevel=100 " 禁止自動摺疊


set laststatus=2 " 開啟狀態欄信息

set cmdheight=2 " 命令行的高度,默認為1,這裡設為2


" 每行超過80個的字符用下劃線標示

au BufRead,BufNewFile *.asm,*.c,*.cpp,*.java,*.cs,*.sh,*.lua,*.pl,*.pm,*.py,*.rb,*.erb,*.hs,*.vim 2match Underlined /.\\%81v/


" 設置編碼

set fenc=utf-8

set encoding=utf-8

"set fileencodings=utf-8,gbk,cp936,latin-1

set fileencodings=utf-8

" 解決菜單亂碼

source $VIMRUNTIME/delmenu.vim

source $VIMRUNTIME/menu.vim

" 解決consle輸出亂碼

language messages zh_CN.utf-8


" For Haskell

:let hs_highlight_delimiters=1 " 高亮定界符

:let hs_highlight_boolean=1 " 把True和False識別為關鍵字

:let hs_highlight_types=1 " 把基本類型的名字識別為關鍵字

:let hs_highlight_more_types=1 " 把更多常用類型識別為關鍵字

:let hs_highlight_debug=1 " 高亮調試函數的名字

:let hs_allow_hash_operator=1 " 阻止把#高亮為錯誤


"只有在是PHP文件時,才啟用PHP補全

au FileType php call AddPHPFuncList()

function AddPHPFuncList()

set dictionary-=/home/feiyan/tools/vim/funclist.txt dictionary+=/home/feiyan/tools/vim/funclist.txt

set complete-=k complete+=k

endfunction


" ======= 恢復上次文件打開位置 ======= "

set viminfo='10,\"100,:20,%,n~/.viminfo

au BufReadPost * if line("'\"") > 0|if line("'\"") <= line("$")|exe("norm'\"")|else|exe "norm $"|endif|endif


set t_ti= t_te=

set hlsearch

if has("autocmd")

au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif

endif


(5).安裝YouCompleteMe'插件


先安裝依賴:

yum -y install cmake centos-release-scl devtoolset-6 scl-utils scl-utils-build scl enable devtoolset-6 bash


在 vim 的配置文件 ~/.vimrc 中添加一行(在call vundle#begin() 和 call vundle#end() 之間)

call vundle#begin()

. . .

Plugin 'Valloric/YouCompleteMe'

. . .

call vundle#end()


vim

執行:

:PluginInstall


安裝YCM如果出現:

The ycmd server SHUT DOWN (restart with ':YcmRestartServer'). YCM core library not detected; you need to compile YCM before using it. Follow the instructions in the documentation.

需要順次執行:

cd ~/.vim/bundle/YouCompleteMe

git submodule update --init --recursive

python3 install.py --clang-completer

然後打開vim執行:

:YcmRestartServer (這步很重要,我老忘記)


安裝YCM如果出現:

YouCompleteMe unavailable no module named frozendict或者 YouCompleteMe unavailable no module named future

原因就是你或者沒用Vundle安裝,或者Vundle由於網速太慢下載到一半不能把安裝依賴包完全下載下來

解決方案:

進入到YouCompleteMe目錄(/root/.vim/bundle/YouCompleteMe),在terminal窗口敲入git submodule update --init --recursive

然後順次執行:

cd ~/.vim/bundle/YouCompleteMe

python3 install.py --clang-completer


至此完成ycm插件的安裝,可以寫一個python看到效果:

golang實戰-1:搭建vim-go開發環境

上圖是筆者寫的一個rocketmq-exporter,可以下載體驗vim,位於:

https://github.com/hepyu/hpy-rocketmq-exporter/tree/master/src


也可以手動安裝看進度:

git clone --recursive https://github.com/Valloric/YouCompleteMe.git ~/.vim/bundle/YouCompleteMe

然後:

cd ~/.vim/bundle/YouCompleteMe

python3 install.py --clang-completer

至此完成安裝。


(6).安裝go插件


我使用的go版本是:

go version go1.13.3 linux/amd64


1.安裝go環境


進入下載頁面:

https://golang.org/dl/


下載最新版本:

wget https://dl.google.com/go/go1.13.3.linux-amd64.tar.gz


解壓:

tar -C /usr/local -xzf go1.13.3.linux-amd64.tar.gz

在/etc/profile中添加環境變量:

export PATH=$PATH:/usr/local/go/bin

然後讓其生效:

source /etc/profile


驗證go是否安裝成功:

go version

go version go1.13.3 linux/amd64


2.修改~/.vimrc


在 vim 的配置文件 ~/.vimrc 中添加一行(在call vundle#begin() 和 call vundle#end() 之間)

call vundle#begin()

. . .

Plugin 'fatih/vim-go'

. . .

call vundle#end()


vim

執行:

:PluginInstall


3.安裝go插件


由於vim-go要下載很多golang的命令,有些需要翻牆,所以我們需要把翻牆的插件換成github上的替代者。


文件位於:~/.vim/bundle/vim-go/plugin/go.vim


let s:packages = {

\\ 'asmfmt': ['github.com/klauspost/asmfmt/cmd/asmfmt'],

\\ 'dlv': ['github.com/go-delve/delve/cmd/dlv'],

\\ 'errcheck': ['github.com/kisielk/errcheck'],

\\ 'fillstruct': ['github.com/davidrjenni/reftools/cmd/fillstruct'],

\\ 'gocode': ['github.com/mdempsky/gocode', {'windows': ['-ldflags', '-H=windowsgui']}],

\\ 'gocode-gomod': ['github.com/stamblerre/gocode'],

\\ 'godef': ['github.com/rogpeppe/godef'],

\\ 'gogetdoc': ['github.com/zmb3/gogetdoc'],

\\ 'goimports': ['golang.org/x/tools/cmd/goimports'],

\\ 'golint': ['golang.org/x/lint/golint'],

\\ 'gopls': ['golang.org/x/tools/gopls@latest', {}, {'after': function('go#lsp#Restart', [])}],

\\ 'golangci-lint': ['github.com/golangci/golangci-lint/cmd/golangci-lint'],

\\ 'gomodifytags': ['github.com/fatih/gomodifytags'],

\\ 'gorename': ['golang.org/x/tools/cmd/gorename'],

\\ 'gotags': ['github.com/jstemmer/gotags'],

\\ 'guru': ['golang.org/x/tools/cmd/guru'],

\\ 'impl': ['github.com/josharian/impl'],

\\ 'keyify': ['honnef.co/go/tools/cmd/keyify'],

\\ 'motion': ['github.com/fatih/motion'],

\\ 'iferr': ['github.com/koron/iferr'],

\\ }


可以看到有如下插件需要翻牆:

'goimports': ['golang.org/x/tools/cmd/goimports'],

'golint': ['golang.org/x/lint/golint'],

'gopls': ['golang.org/x/tools/gopls@latest', {}, {'after': function('go#lsp#Restart', [])}],

'gorename': ['golang.org/x/tools/cmd/gorename'],

'guru': ['golang.org/x/tools/cmd/guru'],


完成包下載需要結合下述三種方法一同使用。


方法一:

由於存在翻牆問題,設置goproxy:

遇到網絡問題:這樣解決,可以把下述配置加入/etc/profile,然後soruce /etc/profile使其生效

# Enable the go modules feature

export GO111MODULE=on

# Set the GOPROXY environment variable

export GOPROXY=https://goproxy.io

然後任意打開一個.go的文件,然後運行 :GoInstallBinaries自動安裝插件。


方法二:可以直接執行:

go get github.com/golang/tools/cmd/goimports

go get github.com/golang/tools/cmd/guru

go get github.com/golang/tools/cmd/gorename


方法三:

先將依賴的項目都git clone到本地。

cd ~/go/src

git clone https://github.com/golang/tools golang.org/x/tools

然後~/go/src下執行:

go install golang.org/x/tools/cmd/goimports

go install golang.org/x/tools/cmd/guru

go install golang.org/x/tools/cmd/gorename


golint需要修改go.vim:

'golint': ['github.com/golang/lint/golint'],

'gopls': ['github.com/golang/tools/gopls@latest', {}, {'after': function('go#lsp#Restart', [])}],


golint在github上是golang/lint項目下的目錄,所以要在~/go/src下執行:

git clone https://github.com/golang/lint.git golang.org/x/lint

執行:

go install golang.org/x/lint


在~/go/src下執行命令下載gopls:

git clone https://github.com/golang/tools/gopls golang.org/x/tools/gopls

gopls本身需要翻牆,另外還依賴很多別的項目,需要:

git clone https://github.com/sergi/go-diff.git sergi/go-diff

git clone https://github.com/BurntSushi/toml BurntSushi/toml

git clone https://github.com/golang/sync.git golang.org/x/sync

git clone https://github.com/golang/xerrors.git golang.org/x/xerrors

git clone https://github.com/golang/tools golang.org/x/tools

最後執行:

go install golang.org/x/tools/gopls

完成gopls


其餘插件類似這樣處理,或者:

任意打開一個.go的文件,然後運行 :GoInstallBinaries自動安裝插件。

效果:

golang實戰-1:搭建vim-go開發環境

注意上圖pakcage是亂碼,crt的問題,換成xshell就OK了:

golang實戰-1:搭建vim-go開發環境

注意最後一行表示成功:

golang實戰-1:搭建vim-go開發環境


(7).安裝樹形目錄插件


vim ~/.vimrc,增加:


call vundle#begin()

Plugin 'scrooloose/nerdtree'

call vundle#end()


然後打開vim,執行命令:PluginInstall安裝插件。


安裝好後,命令行中輸入vim,打開vim後,在vim中輸入:NERDTree,你就可以看到NERDTree的效果了。

golang實戰-1:搭建vim-go開發環境


為方便起見,直接 vim ~/.vimrc 然後添加:


"F2開啟和關閉樹"

map :NERDTreeToggle

let NERDTreeChDirMode=1

"顯示書籤"

let NERDTreeShowBookmarks=1

"設置忽略文件類型"

let NERDTreeIgnore=['\\~$', '\\.pyc$', '\\.swp$']

"窗口大小"

let NERDTreeWinSize=25


這樣打開vim後,只要按鍵盤上的F2就可以顯示和隱藏NERDTree的文件瀏覽了。


如何修改快捷鍵命令,參考官方:

https://github.com/ycm-core/YouCompleteMe#the-gycm_key_invoke_completion-option

比如mac筆記本默認是ctrl+space與mac os衝突,我們需要修改:

let g:ycm_key_invoke_completion = ''

放到~/.vimrc下即可,快捷鍵:ctrl+n。


常用快捷命令:

#快捷方式 切換工作臺和目錄

ctrl + w + h 光標 focus 左側樹形目錄

ctrl + w + l 光標 focus 右側文件顯示窗口

ctrl + w + w 光標自動在左右側窗口切換

ctrl + w + r 移動當前窗口的佈局位置

o 在已有窗口中打開文件、目錄或書籤,並跳到該窗口

go 在已有窗口 中打開文件、目錄或書籤,但不跳到該窗口

t 在新 Tab 中打開選中文件/書籤,並跳到新 Tab

T 在新 Tab 中打開選中文件/書籤,但不跳到新 Tab

i split 一個新窗口打開選中文件,並跳到該窗口

gi split 一個新窗口打開選中文件,但不跳到該窗口

s vsplit 一個新窗口打開選中文件,並跳到該窗口

gs vsplit 一個新 窗口打開選中文件,但不跳到該窗口

! 執行當前文件

O 遞歸打開選中 結點下的所有目錄

x 合攏選中結點的父目錄

X 遞歸 合攏選中結點下的所有目錄

e Edit the current dif

雙擊 相當於 NERDTree-o

中鍵 對文件相當於 NERDTree-i,對目錄相當於 NERDTree-e

D 刪除當前書籤

P 跳到根結點

p 跳到父結點

K 跳到當前目錄下同級的第一個結點

J 跳到當前目錄下同級的最後一個結點

k 跳到當前目錄下同級的前一個結點

j 跳到當前目錄下同級的後一個結點

C 將選中目錄或選中文件的父目錄設為根結點

u 將當前根結點的父目錄設為根目錄,並變成合攏原根結點

U 將當前根結點的父目錄設為根目錄,但保持展開原根結點

r 遞歸刷新選中目錄

R 遞歸刷新根結點

m 顯示文件系統菜單cd 將 CWD 設為選中目錄

I 切換是否顯示隱藏文件

f 切換是否使用文件過濾器

F 切換是否顯示文件

B 切換是否顯示書籤

q 關閉 NerdTree 窗口

? 切換是否顯示 Quick Help


(8).vim常用命令


:PluginList - 枚舉已安裝的插件列表

:PluginInstall - 安裝插件或者後面加上'!'更新

:PluginUpdate - 更新插件 同 :PluginInstall!

:PluginSearch foo - 查找插件。例如查找名稱為foo的插件。或者後面加'!'更新本地緩存

:PluginClean - 清理無用插件或者後面加'!'自動清理


golang實戰-1:搭建vim-go開發環境


分享到:


相關文章: