@@ -133,6 +133,15 @@ M.force_attach = function(bufnr)
133133 M.on_attach(bufnr)
134134end
135135
136+local del_keymaps = function()
137+ local status, autopairs_keymaps = pcall(api.nvim_buf_get_var, 0, 'autopairs_keymaps')
138+ if status and autopairs_keymaps and #autopairs_keymaps > 0 then
139+ for _, key in pairs(autopairs_keymaps) do
140+ pcall(api.nvim_buf_del_keymap, 0, 'i', key)
141+ end
142+ end
143+end
144+
136145local function is_disable()
137146 if M.state.disabled then
138147 return true
@@ -158,9 +167,7 @@ local function is_disable()
158167 end
159168
160169 if utils.check_filetype(M.config.disable_filetype, vim.bo.filetype) then
161− -- should have a way to remove the mapping when vim.bo.filetype = ''
162− -- now we only remove a rule
163− -- the event FileType happen after BufEnter
170+ del_keymaps()
164171 M.set_buf_rule({}, 0)
165172 return true
166173 end
@@ -226,61 +233,40 @@ M.on_attach = function(bufnr)
226233 if utils.is_attached(bufnr) then
227234 return
228235 end
236+ del_keymaps()
229237 local enable_insert_auto = false
238+ local autopairs_keymaps = {}
239+ local expr_map = function(key)
240+ api.nvim_buf_set_keymap(bufnr, 'i', key, '',{
241+ expr = true,
242+ noremap = true,
243+ desc = "autopairs map key",
244+ callback = function() return M.autopairs_map(bufnr, key) end,
245+ }
246+ )
247+ table.insert(autopairs_keymaps, key)
248+ end
230249 for _, rule in pairs(rules) do
231250 if rule.key_map ~= nil then
232251 if rule.is_regex == false then
233252 if rule.key_map == '' then
234253 rule.key_map = rule.start_pair:sub(#rule.start_pair)
235254 end
236− local mapping = string.format(
237− "v:lua.MPairs.autopairs_map(%d,%q)",
238− bufnr,
239− rule.key_map:gsub("<", "<lt>")
240− )
241− api.nvim_buf_set_keymap(
242− bufnr,
243− 'i',
244− rule.key_map,
245− mapping,
246− { expr = true, noremap = true }
247− )
248−
255+ expr_map(rule.key_map)
249256 local key_end = rule.key_end or rule.end_pair:sub(1, 1)
250257 if #key_end >= 1 and key_end ~= rule.key_map and rule.move_cond ~= nil then
251− mapping = string.format(
252− "v:lua.MPairs.autopairs_map(%d,%q)",
253− bufnr,
254− key_end
255− )
256− vim.api.nvim_buf_set_keymap(
257− bufnr,
258− 'i',
259− key_end,
260− mapping,
261− { expr = true, noremap = true }
262− )
258+ expr_map(key_end)
263259 end
264260 else
265261 if rule.key_map ~= '' then
266− local mapping = string.format(
267− "v:lua.MPairs.autopairs_map(%d,%q)",
268− bufnr,
269− rule.key_map:gsub("<", "<lt>")
270− )
271− api.nvim_buf_set_keymap(
272− bufnr,
273− 'i',
274− rule.key_map,
275− mapping,
276− { expr = true, noremap = true }
277− )
262+ expr_map(rule.key_map)
278263 elseif rule.is_endwise == false then
279264 enable_insert_auto = true
280265 end
281266 end
282267 end
283268 end
269+ vim.api.nvim_buf_set_var(bufnr, 'autopairs_keymaps', autopairs_keymaps)
284270
285271 if enable_insert_auto then
286272 -- capture all key use it to trigger regex pairs