Check if current servers have document_formatting enabled

New vim.lsp.buf.format prints the following message when fails:

[LSP] Format request failed, no matching language servers.

I always have format on save enabled, so this message oftentimes annoys me.

Can I somehow check if any of the currently attached servers have document_formatting enabled. And only if yes, vim.lsp.buf.format will be run,

You could define that autocmd inside the on_attach function you passed to lsp client, the function receives a client object which can be used to check it’s capabilities, so you can check if the client supports formatting and then define the mapping and stuff if it does, like:

function on_attach(client, bufnr) {
    if client.supports_method("textDocument/formatting") then
            // Define formatting autocmd or mapping
    end
}
1 Like

Thanks for your suggestion, but I have a shortcut that toggles format on save on the fly by adding/removing the autocommand.

Thus, this won’t work for me.

There’s likely a better way to do this, but this is my hack:

-- Get the list of active lsp clients; pick the first one
-- This will probably fall over in a number of scenarios;
-- if you can get the client another way, do that.
local client = vim.lsp.get_active_clients()[1]

-- Client may be nil
if client then
  -- Check if the server supports formatting
  if client.server_capabilities.documentFormattingProvider then
    -- Sync formatting prevents weird buffer interactions
    vim.lsp.buf.format({ async = false })
  end
end