Simulate a Keypress in Vim

Once in an eternity you need to create a mapping that simulates a keypress.
Here comes the answer:
:h feedkeys()

feedkeys({string} [, {mode}])

Characters in {string} are queued for processing as if they come from a mapping or were typed by the user.

{mode} is a String, which can contain these character flags:

  • 'm' Remap keys. This is default.
  • 'n' Do not remap keys.
  • 't' Handle keys as if typed; otherwise they are handled as if coming from a mapping. This matters for undo, opening folds, etc.
  • 'i' Insert the string instead of appending.

Let's look at simple example:

:call feedkeys("iHello\<CR>Universe!")

Output:

Hello
Universe!

Easiest way to create a mapping for this call - is a function:

function! MyFeedKeys()
  call feedkeys("iHello\<CR>Universe!")
endfunction

nmap C :call MyFeedKeys()<CR>

More complex example of using feedkeys():

" jump to the next snippet trigger or move to the right split
nmap <expr><C-l> neosnippet#jumpable() ?
      \ ":call feedkeys('i<C-l>')<CR>"
      \ : "\<C-w>l"
" jump to the next snippet trigger or redraw a screen
" (default <C-l> behaviour in normal mode)
imap <expr><C-l> neosnippet#jumpable() ?
      \ "\<Plug>(neosnippet_jump)"
      \ : "<ESC>:redraw!<CR>a"

I use neosnippet.vim for adding snippets supports in Vim. In insert mode I use <C-l> for jump to the next snippet trigger. In normal mode I can't jump to the trigger with <Plug>(neosnippet_jump) - it's only works in insert and visual selection modes. That's why I use this workaround with feedkeys() and simulate a keypress for <C-l> in insert mode.