1

I do maintain there mappings in mv $vimrc:

augroup LSP | au!
autocmd FileType go,json,yaml nnoremap <silent> <buffer> <c-]> <cmd>lua vim.lsp.buf.declaration()<CR>
autocmd FileType go,json,yaml nnoremap <silent> <buffer> gd    <cmd>lua vim.lsp.buf.definition()<CR>
autocmd FileType go,json,yaml nnoremap <silent> <buffer> K     <cmd>lua vim.lsp.buf.hover()<CR>

(abbreviated)

However maintaining this becomes tedious: With every language server I add to my system I have to add it on every line next to the autocmd

What I really want is to add these mappings to buffers which have a LS attached. Any way to automatize this?

2

I would suggest to refactor it, introducing a dedicated function that does all the mappings:

func! s:lsp_mappings()
    nnoremap <silent> <buffer> <c-]> <cmd>lua vim.lsp.buf.declaration()<CR>
    nnoremap <silent> <buffer> gd    <cmd>lua vim.lsp.buf.definition()<CR>
    nnoremap <silent> <buffer> K     <cmd>lua vim.lsp.buf.hover()<CR>
endfunc


augroup LSP | au!
    autocmd FileType go,json,yaml call s:lsp_mappings()
augroup END

And to answer your question -- I don't know for sure, but if your LSP implementation (looks like it is builtin neovim lsp?) has some ways to query if lsp is attached to a buffer, then ("pseudocode"):

func! s:lsp_mappings()
    if luaeval('vim.tbl_isempty(vim.lsp.buf_get_clients())') 
        return
    endif

    nnoremap <silent> <buffer> <c-]> <cmd>lua vim.lsp.buf.declaration()<CR>
    nnoremap <silent> <buffer> gd    <cmd>lua vim.lsp.buf.definition()<CR>
    nnoremap <silent> <buffer> K     <cmd>lua vim.lsp.buf.hover()<CR>
endfunc


augroup LSP | au!
    autocmd FileType * call s:lsp_mappings()
augroup END

2
  • 1
    "find a way to query if lsp is attached for a buffer" --> luaeval('vim.tbl_isempty(vim.lsp.buf_get_clients())')
    – Matt
    Sep 13 '20 at 11:03
  • Updated as suggested by @Matt, (didn't test as I don't have neovim with lsp setup at the moment)
    – Maxim Kim
    Sep 13 '20 at 14:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.