Skip to content

Multiple language servers FAQ

Michael Lingelbach edited this page Apr 17, 2022 · 5 revisions

Multiple language servers with the built-in client are supported, however, it is highly recommended to avoid this if possible. Each server attached to a buffer carries a small amount of performance overhead, and the response to each request is overwritten by the previous server's response.

I see multiple formatting options and I want a single server to format, how do I do this?

Consider if you should be mapping the key that calls vim.lsp.buf.formatting(), if (for example) you want to only call a specific server, drop down into the request interface.

local util = require 'vim.lsp.util'

local formatting_callback = function(client, bufnr)
  vim.keymap.set('n', '<leader>f', function()
    local params = util.make_formatting_params({})
    client.request('textDocument/formatting', params, nil, bufnr) 
  end, {buffer = bufnr})
end

lspconfig.clangd.setup {
  on_attach = function(client, bufnr)
    formatting_callback(client, bufnr)
    common_on_attach(client, bufnr)
  end
}

lspconfig.ccls.setup {
  on_attach = function(client, bufnr)
    common_on_attach(client, bufnr)
  end
}

Alternatively, just special case the server:

local util = require 'vim.lsp.util'

local formatting_callback = function(client, bufnr)
  vim.keymap.set('n', '<leader>f', function()
    local params = util.make_formatting_params({})
    client.request('textDocument/formatting', params, nil, bufnr) 
  end, { buffer = bufnr })
end

local servers = {'clangd', 'ccls'}
for _, server in ipairs(servers) do
  lspconfig[server].setup {
    on_attach = function(client, bufnr)
      if client.name ~= 'ccls' then
        formatting_callback(client, bufnr)
      end
      common_on_attach(client, bufnr)
    end
  }
end