From 4af5cf9a8a1883b9f21f5a88309cb941fad8ab88 Mon Sep 17 00:00:00 2001 From: mathew Date: Fri, 18 Aug 2023 20:47:50 +0800 Subject: [PATCH] check modified before format avoid trigger many times --- lua/guard/format.lua | 5 ++++- plugin/guard.lua | 4 ++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/lua/guard/format.lua b/lua/guard/format.lua index 142c88b..caa04c2 100644 --- a/lua/guard/format.lua +++ b/lua/guard/format.lua @@ -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, }) diff --git a/plugin/guard.lua b/plugin/guard.lua index 5be752a..02c1fca 100644 --- a/plugin/guard.lua +++ b/plugin/guard.lua @@ -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 @@ -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