stevearc / conform.nvim

Lightweight yet powerful formatter plugin for Neovim
MIT License
2.89k stars 150 forks source link

feature request: prefer LSP and fallback on formatters #316

Closed fent closed 2 months ago

fent commented 6 months ago

Did you check existing requests?

Describe the feature

I'd prefer to use the LSP formatter if one is available, and fallback on command line formatters. Is there a way to configure the plugin for that?

Provide background

My LSP works great for formatting. But I'd like to provide an alternative just in case the LSP ever disconnects or is unavailable. The command line formatter is much slower than the LSP. I prefer to not use it unless I have to

What is the significance of this feature?

nice to have

Additional details

No response

alsolovyev commented 5 months ago

This behavior can be implemented quite easily in a custom function. For example:

--- Formats buffers using the attached language server clients
--- or using `conform` as a fallback.
local function format()
  local buf_clients = vim.lsp.buf_get_clients()

  -- Check LSP clients that support formatting
  for _, client in pairs(buf_clients) do
    if client.supports_method('textDocument/formatting') then
      vim.lsp.buf.format { async = true }
      return
    end
  end

  -- Fallback on conform
  require('conform').format()
end

vim.keymap.set('n', '<leader>f', format, { desc = 'Format buffers' })
fent commented 5 months ago

Thanks! I'm going to use that for now, but it'd be nice if it was baked in to the plugin

heygarrett commented 3 months ago

I would also like this, but on a per formatter (or file type) basis. In my case I want to prioritize the biome language server over prettierd, but I still want stylua to have priority over lua-language-server.

Edit: I found a workaround by customizing the condition for prettierd:

require("conform").setup({
    formatters = {
        prettierd = {
            condition = function()
                if next(vim.lsp.get_clients({ name = "biome" })) then
                    return false
                end
                -- ...
            end,
        },
    },
})
stevearc commented 2 months ago

I put up a PR that adds support for this. Feel free to check it out; I'll probably merge it in the next few days