Skip to content

Commit

Permalink
fix(#23): improve buffer detach handling (#24)
Browse files Browse the repository at this point in the history
- Refactored buffer detach handling to ensure proper cleanup.
- Added autocmd to disable csvview when buffer is unloaded.
- Improved keymap unregistration with pcall for safety.
  • Loading branch information
hat0uma authored Feb 10, 2025
1 parent 22eb36a commit 9f9aa7e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 8 deletions.
35 changes: 28 additions & 7 deletions lua/csvview/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,15 @@ function M.enable(bufnr, opts)
return
end

-- Create a new CsvView instance and define the on detach callback
local detach_bufevent_handle --- @type fun()
-- Create a new CsvView instance
local on_detach --- @type fun()
local metrics = CsvViewMetrics:new(bufnr, opts)
local view = CsvView:new(bufnr, metrics, opts, function() -- on detach
detach_bufevent_handle()
metrics:clear()
keymap.unregister(opts)
vim.api.nvim_exec_autocmds("User", { pattern = "CsvViewDetach" })
on_detach()
end)

-- Register buffer-update events.
detach_bufevent_handle = buf.attach(bufnr, {
local detach_bufevent_handle = buf.attach(bufnr, {
on_lines = function(_, _, _, first, last, last_updated)
metrics:update(first, last, last_updated)
end,
Expand All @@ -56,6 +53,30 @@ function M.enable(bufnr, opts)
end,
})

-- Define augroup
-- Disable csvview when buffer is unloaded
local group = vim.api.nvim_create_augroup("csvview", { clear = false })
vim.api.nvim_clear_autocmds({ group = group, buffer = bufnr })
vim.api.nvim_create_autocmd("BufUnload", {
callback = function()
if M.is_enabled(bufnr) then
M.disable(bufnr)
end
end,
group = group,
desc = "csvview: disable when buffer is unloaded",
buffer = bufnr,
})

-- Register detach callback
on_detach = function()
vim.api.nvim_clear_autocmds({ group = group, buffer = bufnr })
detach_bufevent_handle()
metrics:clear()
keymap.unregister(opts)
vim.api.nvim_exec_autocmds("User", { pattern = "CsvViewDetach" })
end

-- Calculate metrics and attach view.
metrics:compute_buffer(function()
attach_view(bufnr, view)
Expand Down
2 changes: 1 addition & 1 deletion lua/csvview/keymap.lua
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ function M.unregister(opts)
for _, map in pairs(keymaps) do
local lhs = map[1]
local mode = map.mode
vim.keymap.del(mode, lhs, { buffer = true })
pcall(vim.keymap.del, mode, lhs, { buffer = true })
end
end

Expand Down

0 comments on commit 9f9aa7e

Please sign in to comment.