I agree with the accepted answer.
Something that begins to annoy quickly is that the cursor position is reset to the beginning of the line.
To keep it, one can use getpos
/setpos
like this:
vim.api.nvim_create_autocmd({ "BufWritePre" }, {
pattern = {"*"},
callback = function(ev)
save_cursor = vim.fn.getpos(".")
vim.cmd([[%s/\s\+$//e]])
vim.fn.setpos(".", save_cursor)
end,
})
To catch errors use pcall()
vim.api.nvim_create_autocmd({ "BufWritePre" }, {
pattern = {"*"},
callback = function()
local save_cursor = vim.fn.getpos(".")
pcall(function() vim.cmd [[%s/\s\+$//e]] end)
vim.fn.setpos(".", save_cursor)
end,
})