Skip to content

Commit

Permalink
check modified before format avoid trigger many times
Browse files Browse the repository at this point in the history
  • Loading branch information
glepnir committed Aug 18, 2023
1 parent b1b95d9 commit 4af5cf9
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
5 changes: 4 additions & 1 deletion lua/guard/format.lua
Original file line number Diff line number Diff line change
Expand Up @@ -172,10 +172,13 @@ local function do_fmt(buf)
end

local function attach_to_buf(buf)
api.nvim_create_autocmd('BufWritePost', {
api.nvim_create_autocmd('BufWritePre', {
group = 'Guard',
buffer = buf,
callback = function(opt)
if not vim.bo[opt.buf].modified then
return
end
require('guard.format').do_fmt(opt.buf)
end,
})
Expand Down
4 changes: 2 additions & 2 deletions plugin/guard.lua
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ vim.api.nvim_create_user_command('GuardDisable', function(opts)
local arg = opts.args
local bufnr = (#opts.fargs == 0) and api.nvim_get_current_buf() or tonumber(arg)
if bufnr then
local bufau = api.nvim_get_autocmds({ group = 'Guard', event = 'BufWritePost', buffer = bufnr })
local bufau = api.nvim_get_autocmds({ group = 'Guard', event = 'BufWritePre', buffer = bufnr })
if #bufau ~= 0 then
api.nvim_del_autocmd(bufau[1].id)
end
Expand All @@ -19,7 +19,7 @@ vim.api.nvim_create_user_command('GuardEnable', function(opts)
local arg = opts.args
local bufnr = (#opts.fargs == 0) and api.nvim_get_current_buf() or tonumber(arg)
if bufnr then
local bufau = api.nvim_get_autocmds({ group = 'Guard', event = 'BufWritePost', buffer = bufnr })
local bufau = api.nvim_get_autocmds({ group = 'Guard', event = 'BufWritePre', buffer = bufnr })
if #bufau == 0 then
require('guard.format').attach_to_buf(bufnr)
end
Expand Down

0 comments on commit 4af5cf9

Please sign in to comment.