Mar 14, 2024
One of my main problems with autoclose plugins would be that if I wanted to just enter a single bracket or quote it would be really hard to do so. I’d have to type it, hit Esc
and then delete the autoclosed character. It would get even more complicated if I was trying to fix some sort of formatting and I just wanted to add a specific character without it autoclosing. I was finally able to figure out a good setup of having autoclose but also being able to easily enter single characters.
With the help of the plugin creator of altermo/ultimate-autopair.nvim
, I was able to get a setup working that only triggers an autoclose if you type a subsequent non-closing character. So just typing '
or (
or even ('
and hitting Esc
will not trigger the autoclosing and will just type those characters. The setup is available in my dotfiles but here’s also the code in case you are interested.
local pair=[[([{"']]
local end_pair=[[)]}"']]
local pair_insert
local save={}
local group=vim.api.nvim_create_augroup('test',{})
vim.api.nvim_create_autocmd('InsertCharPre',{callback=function ()
pair_insert=false
for c in pair:gmatch'.' do
if vim.v.char==c then
local action=require'ultimate-autopair.core'.run(c)
if action=='\aU\x80kr'--[[this is dont-new-undo + <right>]] then
vim.api.nvim_feedkeys(action,'n',false)
vim.v.char=''
save={}
return
elseif #action>2 then
table.insert(save,action:sub(3))
pair_insert=true
return
end
end
end
if not save[1] then return end
local nsave=save
save={}
if end_pair:find(vim.v.char,1,true) then return end
vim.api.nvim_feedkeys(table.concat(nsave),'n',false)
end,group=group})
vim.api.nvim_create_autocmd('CursorMovedI',{callback=function ()
if pair_insert then return end
save={}
end,group=group})
vim.api.nvim_create_autocmd('ModeChanged',{callback=function () save={} end,group=group})
for c in pair:gmatch'.' do
vim.keymap.del('i',c)
end
You can also check out the github issue. Hope this helps. God bless!