I just learned about vimscript. I'm trying to write a small vimscript that'll kinda copy what this does, but more verbosely and very explicitly. (The first case would case typing a ( will insert ())

" make keymappings
for [opener, closer] in {'(': ')'}
  inoremap l:opener <C-r>=InsertPair(opener, closer)<CR>

" Typing the opener will also insert the closer
function! InsertPair(open, close)
  return a:open . a:close . "\<Left>"

But I ran into a problem. The inoremaps aren't working as planned - they're remapping the literal chars l : o p e n e r instead of the value of the local variable named opener (().

Is dereferencing a variable in a call to map possible in vimscript?

1 Answer 1


So close! Use the "= register again. What that looks like for your question is

inoremap <C-r>=opener<CR> <C-r>=InsertPair(opener, closer)<CR><CR>

If you want to lock in the values of the variable at runtime then you can also do something like this:

execute "inoremap " . opener . " <C-r>=InsertPair('" . opener . "', '" . closer . "')<CR>"
  • 2
    You could also use printf (it might be sprintf?) to simplify the string passes to exec (ie use formatting replacements rather than tough to read concatenation)
    – D. Ben Knoble
    Commented Sep 4, 2018 at 13:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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