Sam Phillips
Sam Phillips

Reputation: 265

Custom binding to wrap selection in parentheses

I have a nifty key combination to wrap a single word in parentheses: cw(<C-r><C-o>")<ESC>.

What I want to do is create a custom binding, (, which operates on any selection.

If I am in visual mode and have selected a block of text or several blocks, ( should wrap all of the selected blocks in parentheses.

If I am in normal mode and type (3j, it should perform the combination c3j(<C-r><C-o>")<ESC>.

Thank you for your help.

Upvotes: 3

Views: 147

Answers (1)

Hauleth
Hauleth

Reputation: 23586

What you need is 'opfunc' and g@ mappings for normal mode. So it would look like:

function WrapInParens(type, ...) abort
  let sel_save = &selection
  let &selection = "inclusive"
  let reg_save = @@

  if a:0  " Invoked from Visual mode, use gv command.
    silent exe "normal! gvc(\<C-r>\<C-o>\")"
  elseif a:type == 'line'
    silent exe "normal! '[V']c(\<C-r>\<C-o>\")"
  else
    silent exe "normal! `[v`]c(\<C-r>\<C-o>\")"
  endif

  let &selection = sel_save
  let @@ = reg_save
end

nnoremap ( :set opfunc=WrapInParens<CR>g@

Or similar. This should give you overview (I haven't tested it)


However there are 2 plugins that offers such functionality without overriding (:

Upvotes: 7

Related Questions