From 01d976117743876f1c102bda2a03d93c7a37d85f Mon Sep 17 00:00:00 2001 From: Marco Fernandez Date: Tue, 24 Sep 2024 09:47:57 -0400 Subject: [PATCH] feat: improve default formatters Closes #304 --- README.md | 4 +++- doc/formatter.txt | 5 ++++- lua/formatter/filetypes/any.lua | 11 ++++++++++- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 757e5f8..009a6df 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,9 @@ require("formatter").setup { ["*"] = { -- "formatter.filetypes.any" defines default configurations for any -- filetype - require("formatter.filetypes.any").remove_trailing_whitespace + require("formatter.filetypes.any").remove_trailing_whitespace, + -- Remove trailing whitespace without 'sed' + -- require("formatter.filetypes.any").substitute_trailing_whitespace, } } } diff --git a/doc/formatter.txt b/doc/formatter.txt index 2e4f4ee..b623a9b 100644 --- a/doc/formatter.txt +++ b/doc/formatter.txt @@ -117,7 +117,10 @@ Setup: ["*"] = { -- "formatter.filetypes.any" defines default configurations for any -- filetype - require("formatter.filetypes.any").remove_trailing_whitespace + require("formatter.filetypes.any").remove_trailing_whitespace, + + -- Remove trailing whitespace without 'sed' + -- require("formatter.filetypes.any").substitute_trailing_whitespace, } } } diff --git a/lua/formatter/filetypes/any.lua b/lua/formatter/filetypes/any.lua index 525ac43..8388759 100644 --- a/lua/formatter/filetypes/any.lua +++ b/lua/formatter/filetypes/any.lua @@ -6,7 +6,16 @@ local util = require "formatter.util" M.remove_trailing_whitespace = util.withl(defaults.sed, "[ \t]*$") M.substitute_trailing_whitespace = function() - vim.cmd([[silent! :keeppatterns %s/\[ \t]+$//ge]]) + local line, col = unpack(vim.api.nvim_win_get_cursor(0)) + + vim.cmd [[silent! :keeppatterns %s/[ \t]\+$//ge]] + + -- Restore cursor position without going out of bounds + local lastline = vim.fn.line "$" + if line > lastline then + line = lastline + end + vim.api.nvim_win_set_cursor(0, { line, col }) end return M