mcauley-penney / tidy.nvim

A small Neovim plugin to remove trailing whitespace and empty lines at end of file on every save
107 stars 15 forks source link

Also Remove Unnecessary Leading Whitespace #7

Closed amarakon closed 2 years ago

amarakon commented 2 years ago

Use this C program as an example:

 #include <stdio.h>

int main(void)
{
    printf("%s\n", "Hello world");
}

Notice the unnecessary leading space in front of #include <stdio.h>. After writing to the file, the result should be this:

#include <stdio.h>

int main(void)
{
    printf("%s\n", "Hello world");
}

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.

mcauley-penney commented 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.

amarakon commented 2 years ago

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.

mcauley-penney commented 2 years ago

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.

amarakon commented 2 years ago

What exactly is client supposed to be in that example? It gave me an error because that variable does not exist.