From 23525dd4e3d7daaf619ab5a484ad45693a885975 Mon Sep 17 00:00:00 2001 From: Oleh Kostiuk Date: Wed, 5 Aug 2026 20:06:28 +0200 Subject: [PATCH] fix(editorconfig): avoid trim_trailing_whitespace in insert-mode #41175 Problem: During insert-mode / replace-mode, `autowrite` may trigger. If it does, the cursor position can shift due to the automatic removal of trailing spaces on the current line. When I resume typing, the space between the last word and the new word is suddenly gone. Solution: Disable the "remove trailing spaces" handler during Insert (or a similar) mode. Autosave logic is not affected. --- runtime/lua/editorconfig.lua | 4 +++ test/functional/plugin/editorconfig_spec.lua | 34 ++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/runtime/lua/editorconfig.lua b/runtime/lua/editorconfig.lua index 537a5f1a44..90baf784dc 100644 --- a/runtime/lua/editorconfig.lua +++ b/runtime/lua/editorconfig.lua @@ -166,6 +166,10 @@ function properties.trim_trailing_whitespace(bufnr, val) ) if val == 'true' then nvim_on('BufWritePre', 'nvim.editorconfig', { buf = bufnr }, function() + local mode = vim.api.nvim_get_mode().mode + if mode:sub(1, 1) == 'i' or mode:sub(1, 1) == 'R' or mode:sub(1, 2) == 'ni' then + return + end local view = vim.fn.winsaveview() vim.api.nvim_command('silent! undojoin') vim.api.nvim_command('silent keepjumps keeppatterns %s/\\s\\+$//e') diff --git a/test/functional/plugin/editorconfig_spec.lua b/test/functional/plugin/editorconfig_spec.lua index fa079f9a88..7e7b8b9220 100644 --- a/test/functional/plugin/editorconfig_spec.lua +++ b/test/functional/plugin/editorconfig_spec.lua @@ -9,6 +9,7 @@ local eq = t.eq local pathsep = n.get_pathsep() local fn = n.fn local api = n.api +local feed = n.feed local testdir = 'Xtest-editorconfig' @@ -100,6 +101,15 @@ setup(function() [no_trim.txt] trim_trailing_whitespace = false + [skip_trim_when_insert.txt] + trim_trailing_whitespace = true + + [skip_trim_when_replace.txt] + trim_trailing_whitespace = true + + [skip_trim_when_insert_normal.txt] + trim_trailing_whitespace = true + [max_line_length.txt] max_line_length = 42 @@ -211,6 +221,30 @@ But not this one command('write') command('bdelete') eq(untrimmed, t.read_file(filename)) + + filename = testdir .. pathsep .. 'skip_trim_when_insert.txt' + t.write_file(filename, untrimmed) + command('edit ' .. filename) + command('startinsert') + command('write') + command('bdelete') + eq(untrimmed, t.read_file(filename)) + + filename = testdir .. pathsep .. 'skip_trim_when_replace.txt' + t.write_file(filename, untrimmed) + command('edit ' .. filename) + command('startreplace') + command('write') + command('bdelete') + eq(untrimmed, t.read_file(filename)) + + filename = testdir .. pathsep .. 'skip_trim_when_insert_normal.txt' + t.write_file(filename, untrimmed) + command('edit ' .. filename) + command('startinsert') + feed(':write') + command('bdelete') + eq(untrimmed, t.read_file(filename)) end) it('sets textwidth', function()