windwp / nvim-autopairs

autopairs for neovim written in lua

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is there a way to prevent autocomplete if Esc is pressed?

sainttttt opened this issue · comments

Hi! I'd like it so that if I press Esc (leaving insert mode) without entering another subsequent character, the autocomplete won't trigger. So for example just entering (<Esc> would end up with ( or ('<Esc> would give me (', but entering ('h<Esc> would give me ('h'). Would this be possible at all? I sort of have this functionality with some basic vim mappings as follows:

imap [<esc> <c-v>[<esc>
imap ['<esc> <c-v>[<c-v>'<esc>
imap ["<esc> <c-v>[<c-v>"<esc>
imap ']<esc> <c-v>'<c-v>]<esc>
imap "]<esc> <c-v>"<c-v>]<esc>

imap {<esc> <c-v>{<esc>
imap {'<esc> <c-v>{<c-v>'<esc>
imap {"<esc> <c-v>{<c-v>"<esc>
imap '}<esc> <c-v>'<c-v>}<esc>
imap "}<esc> <c-v>"<c-v>}<esc>

imap (<esc> <c-v>(<esc>
imap ('<esc> <c-v>(<c-v>'<esc>
imap ("<esc> <c-v>(<c-v>"<esc>
imap ')<esc> <c-v>'<c-v>)<esc>
imap ")<esc> <c-v>"<c-v>)<esc>

imap '<esc> <c-v>'<esc>
imap "<esc> <c-v>"<esc>

imap "" <c-v>"<c-v>"

But the main issue being is that for multiple char imappings, it doesn't show all the characters on the screen as you type, but just one at a time, which is a bit jarring. Any help would be appreciated.

Thanks!

commented

There isn't really a nice way to prevent the autocomplete from happening for Esc, but you could instead make Esc delete end pairs if the pairs are empty.

-- lua
local is_pair = {
    ['{}'] = true,
    ['[]'] = true,
    ['\'\''] = true,
    ['\"\"'] = true,
    ['[\'\']'] = true,
    ['[\"\"]'] = true,
    ['{\'\'}'] = true,
    ['{\"\"}'] = true,
}
vim.keymap.set('i', '<esc>', function()
    local line = vim.api.nvim_get_current_line()
    local col = vim.api.nvim_win_get_cursor(0)[2] + 1
    -- {""}
    --   |
    -- The cursor is |
    if is_pair[line:sub(col - 2, col + 1)] then
        -- del deletes the character on the cursor
        return '<del><del><esc>'
    end
    -- {}
    --  |
    if is_pair[line:sub(col - 1, col)] then
        return '<del><esc>'
    end
    return '<esc>'
end, { expr = true })

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@Sam-programs the mapping doesn't seem to work for me. It doesn't seem like I can map anything to my key. Do you know of a way to make it work?