VimでGoの開発環境を構築する
必要なもの
dein.vim
Vimプラグインの管理
vim-lsp
LSPクライアント
ale
gofmtの非同期実行
asyncomplete.vim
自動補完用
asyncomplete-lsp.vim
gopls
GoのLSPサーバ
依存プラグインのインストール
dein.vimを使用して、依存プラグインをインストールします
code:dein.toml
plugins
repo = 'dense-analysis/ale'
on_cmd = 'ALEFix', 'ALEFixSuggest', 'ALELint', 'ALEToggle', 'ALEEnable', 'ALEToggleBuffer', 'ALEEnableBuffer'
on_func = 'ale#completion#OmniFunc'
depends = 'asyncomplete.vim'
on_source = 'asyncomplete.vim'
hook_source = 'source path/to/ale.rc.vim'
plugins
repo = 'prabirshrestha/vim-lsp'
on_func = 'lsp#enable'
hook_source = 'source path/to/lsp.rc.vim'
plugins
repo = 'prabirshrestha/asyncomplete-lsp.vim'
depends = 'asyncomplete.vim'
on_source = 'vim-lsp'
plugins
repo = 'prabirshrestha/asyncomplete.vim'
on_func = 'asyncomplete#enable_for_buffer'
hook_source = 'source path/to/asyncomplete.rc.vim'
補足
プラグインごとの設定を独立して管理したいため、on_sourceで設定ファイルの読み込みを行っています(path/to/*.rc.vimの箇所は適宜置き換えください)
uki00a.iconはプラグインの遅延読み込みがしたいため、on_cmdやon_func等を使っています
aleのセットアップ
ALEFixコマンドでgofmtを実行するよう設定します
code:ale.rc.vim
let g:ale_fixers = {}
" ...省略...
let g:ale_fixers'go' = 'gofmt'
vim-lspのセットアップ
goplsを使うよう、vim-lspを設定します
code:lsp.rc.vim
if executable("gopls")
augroup LspGo
autocmd!
autocmd User lsp_setup call lsp#register_server({
\ "name": "go-lang",
\ "cmd": {server_info -> "gopls"},
\ "whitelist": "go",
\ "workspace_config": {
\ "gopls": {
\ "staticcheck": v:true,
\ "completeUnimported": v:true,
\ "caseSensitiveCompletion": v:true,
\ "usePlaceholders": v:true,
\ "completionDocumentation": v:true,
\ "watchFileChanges": v:true,
\ "hoverKind": "SingleLine",
\ }},
\ })
augroup END
endif
キーマッピング
以下のような設定をvimrc/init.vimに記載し、vim-lspやaleの各コマンドや関数を呼び出せるようにしています
code:init.vim
function! s:EnableLsp() abort
call lsp#enable()
echomsg "vim-lsp enabled"
endfunction
nmap <Leader>l lsp
nmap <Leader>a ale
" <Leader>leでvim-lspを有効化
nmap <silent> lspe :<C-u>call <SID>EnableLsp()<CR>
" <Leader>ldでvim-lspを無効化
nmap <silent> lspd :<C-u>call lsp#disable()<CR>
" <Leader>alで<Plug>(ale_lint)を実行する
nmap <silent> alel <Plug>(ale_lint)
" <Leader>afで<Plug>(ale_fix)を実行する
nmap <silent> alef <Plug>(ale_fix)
参考
vim-goを使わず、LSP(gopls)を使ってVimのGo開発環境を構築する