Open3

vim-lspの設定をした際のメモ

Shotaro TsujiShotaro Tsuji

VimのLanguage Server Protocolプラグインであるvim-lspをインストールした際のメモです。

まずは.vimrc

call plug#begin('~/.vim/plugged')
"...snip...
Plug 'prabirshrestha/vim-lsp'
"...snip...
call plug#end

を書いて保存する。Vimを再起動してから:PlugInstallを実行してvim-lspをインストールする。

vim-lspのリポジトリにあるサンプルを参考にして.vimrcを編集する。

rust-analyzerを使うのでlsp#register-serverの部分はrust-analyzerを使うように書き直す。

デフォルトでは左端にdiagnosticsなどを表示するための領域が出てくるので、

setlocal signcolumn=no

に書き換える。これで左端の列が消える。

:LspHoverで出てくるポップアップウィンドウをスクロールするためのキーのマップを行うが、サンプルではinoremapを使っていて、このままではインサートモードでのキーマップになってしまう。これをnnoremapに書き換えてノーマルモードで使えるようにする。この問題はIssue #1161で話題に上がっているが、README.mdはなぜか修正されていない。

Shotaro TsujiShotaro Tsuji

vim-lspに関する設定は以下のようになった。

if executable('rust-analyzer')
    au User lsp_setup call lsp#register_server({
        \ 'name': 'Rust Language Server',
	\ 'cmd': {server_info->['rust-analyzer']},
        \ 'whitelist': ['rust'],
        \ })
endif

function! s:on_lsp_buffer_enabled() abort
    setlocal omnifunc=lsp#complete
    setlocal signcolumn=no
    if exists('+tagfunc') | setlocal tagfunc=lsp#tagfunc | endif
    nmap <buffer> gd <plug>(lsp-definition)
    nmap <buffer> gs <plug>(lsp-document-symbol-search)
    nmap <buffer> gS <plug>(lsp-workspace-symbol-search)
    nmap <buffer> gr <plug>(lsp-references)
    nmap <buffer> gi <plug>(lsp-implementation)
    nmap <buffer> gt <plug>(lsp-type-definition)
    nmap <buffer> <leader>rn <plug>(lsp-rename)
    nmap <buffer> [g <plug>(lsp-previous-diagnostic)
    nmap <buffer> ]g <plug>(lsp-next-diagnostic)
    nmap <buffer> K <plug>(lsp-hover)
    nnoremap <buffer> <expr><c-f> lsp#scroll(+4)
    nnoremap <buffer> <expr><c-d> lsp#scroll(-4)

    let g:lsp_diagnostics_enabled = 0
    let g:lsp_diagnostics_signs_enabled = 0
    let g:lsp_document_highlight_enabled = 0
    let g:lsp_document_code_action_signs_enabled = 0

    let g:lsp_format_sync_timeout = 1000
    autocmd! BufWritePre *.rs,*.go call execute('LspDocumentFormatSync')

    " refer to doc to add more commands
endfunction

augroup lsp_install
    au!
    " call s:on_lsp_buffer_enabled only for languages that has the server registered.
    autocmd User lsp_buffer_enabled call s:on_lsp_buffer_enabled()
augroup END