11

I can already map a key combination in insert mode:

:inoremap abc <do stuff>

However, this has a few drawbacks:

  • When typing a partial version of the sequence, such as ab, the characters aren't actually displayed for a short amount of time, since it's "waiting" to see whether you're going to type the full command. This is undesirable; I want to map a chain of letters without pausing if a partial substring of the chain is entered.

  • If I type ab, then pause (and wait until the characters actually appear as mentioned in the above point), then type the c, the command is not executed. I want the command to be executed no matter how long I wait.

I would use an iab, but that doesn't work because:

  1. It requires entering a space after the string
  2. I can't execute arbitrary commands with it, only insert a string of text.

Is there any way to execute a command or keystrokes if a certain string is entered in insert mode, without using a map (which will annoyingly pause every time I type an a and not work if I wait too long)?

  • These drawbbacks are also true for :cnoremap abc <do stuff>... – Martin Tournoij Feb 7 '15 at 2:08
  • 1
    There's no delay when you do ab<any key>. – romainl Feb 7 '15 at 10:26
10

Here's one way to do that:

let s:inputBuffer = ''

augroup _silentInsertTrigger
    autocmd!
    autocmd InsertCharPre * call <sid>OnPreEnterChar()
    autocmd InsertLeave * call <sid>OnInsertLeave()
augroup END

function! s:OnPreEnterChar()
    let s:inputBuffer .= v:char

    if s:inputBuffer[-3:] ==# 'abc'
        echo '<do stuff>'
    endif

    return v:char
endfunction

function! s:OnInsertLeave()
    let s:inputBuffer = ''
endfunction

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.