2

I am trying to create a function in vim that is capable of creating mappings for me. This is so I don't have to type out very similar commands over and over in my vimrc.

Take these two mappings as examples...

onoremap <buffer> in( :<c-u>execute "normal! /(\r:noh\rvi("<cr>
onoremap <buffer> in[ :<c-u>execute "normal! /[\r:noh\rvi["<cr>

(these are operator-pending mappings for in paren or square bracket)

What the mappings do is not really important for the question, what I would like to know is if I can create a function to remove all the repetition. I would like it to look something like...

CreateNextIn('(')
CreateNextIn('[')
CreateNextIn('{')

which will create the omap for me.

Any help will be greatly appreciated :D

1
  • 2
    Build mapping as a concatenation of things that don't change as static strings and the things that change as sub-expressions/variables and pass the whole thing to :exe... :exe 'nnoremap <leader>' . mapkey . ' :echo "' . somevar . '"<cr>'
    – B Layer
    Jul 11, 2020 at 12:11

1 Answer 1

3

Thanks to @B Layer's comment...

Build mapping as a concatenation of things that don't change as static strings and the things that change as sub-expressions/variables and pass the whole thing to :exe... :exe 'nnoremap <leader>' . mapkey . ' :echo "' . somevar . '"<cr>'

I have been able to answer the question.

Here is the solution to the above problem...

function CreateNextIn(str)
  execute 'onoremap <buffer> in' . a:str . ' :<c-u>execute "normal! /' . a:str . '\r:noh\rvi' . a:str . '"<cr>'
endfunction
3

Your Answer

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

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