Skip to content

Instantly share code, notes, and snippets.

@jondkinney
Created August 6, 2025 22:40
Show Gist options
  • Save jondkinney/227b15b95211e5db8b517142824c1e6e to your computer and use it in GitHub Desktop.
Save jondkinney/227b15b95211e5db8b517142824c1e6e to your computer and use it in GitHub Desktop.
Undo History Refined
-- Disable undo history for LSP formatting/code actions
-- This prevents import organization and formatting from cluttering undo history
---@type LazySpec
return {
"AstroNvim/astrolsp",
opts = {
autocmds = {
format_on_save_preserve_undo = {
{
event = "BufWritePre",
desc = "Preserve undo history during LSP formatting",
callback = function(args)
-- Only proceed if format on save is enabled
local astrolsp = require "astrolsp"
if not astrolsp.config.formatting.format_on_save.enabled then return end
-- Get the current buffer's filetype
local ft = vim.bo[args.buf].filetype
-- Check if we should preserve undo for this filetype
local affected_filetypes = {
typescript = true,
typescriptreact = true,
javascript = true,
javascriptreact = true,
}
if affected_filetypes[ft] then
-- Save the current undo tree to a temporary file
local tmpfile = vim.fn.tempname()
vim.cmd("wundo! " .. tmpfile)
-- Store the temp file path in buffer variable for restoration
vim.b[args.buf].undo_tmpfile = tmpfile
-- Clear undo history
local undolevels = vim.o.undolevels
vim.o.undolevels = -1
vim.o.undolevels = undolevels
end
end,
},
{
event = "BufWritePost",
desc = "Restore undo history after LSP formatting",
callback = function(args)
-- Check if we saved undo history for this buffer
if vim.b[args.buf].undo_tmpfile then
local tmpfile = vim.b[args.buf].undo_tmpfile
-- Restore the undo tree from the temporary file
if vim.fn.filereadable(tmpfile) == 1 then
vim.cmd("silent! rundo " .. tmpfile)
-- Clean up the temp file
vim.fn.delete(tmpfile)
end
-- Clear the buffer variable
vim.b[args.buf].undo_tmpfile = nil
end
end,
},
},
},
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment