lukas-reineke / lsp-format.nvim

A wrapper around Neovims native LSP formatting.
559 stars 27 forks source link

Format-on-save doesn't work, but calling `:lua vim.lsp.buf.format()` does #70

Closed beneyal closed 1 year ago

beneyal commented 1 year ago

Hello! 👋

This is probably a silly question, but I just can't seem to format-on-save. I'm using Neovim 0.8.2 on Ubuntu 22.04 (WSL). I couldn't find a similar issue, so I'm submitting this one.

My config looks something like this:

require("lsp-format").setup {}

--  This function gets run when an LSP connects to a particular buffer.
local on_attach = function(client, bufnr)
  -- ...keymaps...

  -- Enable format-on-save
  require("lsp-format").on_attach(client)
end

local servers = {
  pyright = {},
  tsserver = {},
}

local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities = require('cmp_nvim_lsp').default_capabilities(capabilities)

-- Setup mason so it can manage external tooling
require('mason').setup()

-- Ensure the servers above are installed
local mason_lspconfig = require 'mason-lspconfig'

mason_lspconfig.setup {
  ensure_installed = vim.tbl_keys(servers),
}

mason_lspconfig.setup_handlers {
  function(server_name)
    require('lspconfig')[server_name].setup {
      capabilities = capabilities,
      on_attach = on_attach,
      settings = servers[server_name],
    }
  end,
}

I'm using null-ls to provide the formatting to the LSP, and apparently it works, since I can manually format using vim.lsp.buf.format().

I checked :autocmd BufWritePre and :autocmd BufWritePost. The first is empty, the second has some autocmds, but none related to formatting.

Is there anything else I'm missing here?

Thank you for your help, and for the plugin 🙏

beneyal commented 1 year ago

Problem solved, it seems. For posterity:

null-ls's .setup has its own on_attach handler, which (apparently?) doesn't use lspconfig's on_attach. So files that were not handled by null-ls used lsp-format correctly, but files that are handled by null-ls did not.

I made my null-ls.lua file look like this:

local null_ls = require("null-ls")

null_ls.setup({
  sources = {
    null_ls.builtins.formatting.black,
    null_ls.builtins.formatting.isort,
    null_ls.builtins.formatting.stylua,
  },
  on_attach = function(client, _)
    require("lsp-format").on_attach(client)
  end,
})

and now it seems everything uses lsp-format as it should 🙂