From b8d5c93017ad094a3089c5f962a9b9519bf1964c Mon Sep 17 00:00:00 2001 From: champignoom Date: Wed, 3 Jan 2024 00:58:28 +0800 Subject: [PATCH] feat(indent): add new undo block before indenting upon pressing esc --- .../modules/core/esupports/indent/module.lua | 25 +++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/lua/neorg/modules/core/esupports/indent/module.lua b/lua/neorg/modules/core/esupports/indent/module.lua index 795e9b599..4e88b4b07 100644 --- a/lua/neorg/modules/core/esupports/indent/module.lua +++ b/lua/neorg/modules/core/esupports/indent/module.lua @@ -303,10 +303,15 @@ module.config.public = { module.load = function() module.required["core.autocommands"].enable_autocommand("BufEnter") + module.required["core.autocommands"].enable_autocommand("InsertLeave") end module.on_event = function(event) - if event.type == "core.autocommands.events.bufenter" and event.content.norg then + if not event.content.norg then + return + end + + if event.type == "core.autocommands.events.bufenter" then vim.api.nvim_buf_set_option( event.buffer, "indentexpr", @@ -315,14 +320,30 @@ module.on_event = function(event) local indentkeys = "o,O,*,*" .. lib.when(module.config.public.format_on_enter, ",*", "") - .. lib.when(module.config.public.format_on_escape, ",*", "") vim.api.nvim_buf_set_option(event.buffer, "indentkeys", indentkeys) + elseif event.type == "core.autocommands.events.insertleave" then + if module.config.public.format_on_escape then + vim.api.nvim_buf_call(event.buffer, function() + if event.line_content == "" then + return + end + + local lineno_1b = event.cursor_position[1] + local old_indent = vim.fn.indent(lineno_1b) + local new_indent = module.public.indentexpr(0, lineno_1b - 1) + if old_indent ~= new_indent then + vim.bo.undolevels = vim.bo.undolevels + vim.api.nvim_buf_set_text(0, lineno_1b-1, 0, lineno_1b-1, old_indent, { (" "):rep(new_indent) }) + end + end) + end end end module.events.subscribed = { ["core.autocommands"] = { bufenter = true, + insertleave = true, }, }