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?

Edit: here's a link to the full script


This is a slightly circuitious way to solve your problem, but you're looking for the execute command. I don't know of a way to interpret the "literal keystrokes to remap" part of the keymapping command as a variable (A bummer... but makes sense)

You can 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 Sep 4 '18 at 13:38

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.