Closed amarakon closed 2 years ago
Tools like Treesitter, LSP, and formatters are perfect for this kind of thing. It's definitely possible to remove leading white spaces using vim regex, but determining which places to remove white space from would require a lot of rules - the regex would become massive, I think, and would only apply to a given language. All of that to say, it's unnecessary and impractical to do that in this plugin.
In my setup, I handle this using formatters and LSP. For example, I use Clangd for C and it handles this kind of thing on every save.
In my setup, I handle this using formatters and LSP. For example, I use Clangd for C and it handles this kind of thing on every save.
Can you please show me how I can do this? I have nvim-lspconfig and clangd installed.
The tool you'll want to use is vim.lsp.buf.format()
. In your lspconfig setup, you could use something like:
local grp = vim.api.nvim_create_augroup("OnSave", { clear = true })
if client.supports_method("textDocument/formatting") then
vim.api.nvim_create_autocmd("BufWritePre", {
group = grp,
buffer = vim.api.nvim_get_current_buf(),
callback = function()
vim.lsp.buf.format()
end,
})
end
As a forewarning, I haven't tested this and my setup is a little bit different. Basically, you're checking if the LSP supports formatting and, if it does, you set up an autocommand to format on save.
What exactly is client
supposed to be in that example? It gave me an error because that variable does not exist.
Use this C program as an example:
Notice the unnecessary leading space in front of
#include <stdio.h>
. After writing to the file, the result should be this:The leading whitespace in front of
printf
should not be deleted because it is used for indentation. This should work if someone indents with tabs or spaces. I am not sure how to implement this myself, so I am opening an issue instead of a pull request.