I tried to make a function
function! WrapSelect (front, back) "puts characters around the selected text. execute '''<, ''>s/\%V\(\_.*\)\%V\(\_.\)/'.a:front.'\1\2'.a:back.'/' nohl endfunction vnoremap <C-l> :call WrapSelect('[',']')<cr>
The reason there's a second group is to make it behave like yank: I want to put the brackets around the selected text, including the character under the cursor, the way yank copies selected text.
Example input (where | denotes highlighted section):
a|nd then some words and some other wor|ds
a[nd then some words and some other wor]ds
Actual output: an error message:
Error detected while processing function WrapSelect: line 15: E19: Mark has invalid line number Press ENTER or type command to continue
and the text becomes
a[nd then some words and some other wor][ds ]
With more lines in the file unselected the output becomes more garbage:
a[[nd then some words and some other wor][ds third line ] fifth line ]sixth line
Reading about substitute says that it does the search on each line in the selected range, and I don't see a way to turn that off and just do it on the whole block once.
function! WrapSelect (front, back) "puts characters around the selected text. execute "normal gv" . 'c'.a:front.'^R"'.a:back endfunction vnoremap <C-l> :call WrapSelect('[',']')<cr>
where ^R is the literal C-r from Ctrl+v Ctrl+r (it didn't paste into SE)
This produces different wrong output:
a[[nd then some words] and some other wor]ds
This one seemed more promising from reading the help docs (
:h i_CTRL-R), but still did not do what I expected.
I know plugins exist that can do cooler things than I can, but I would like to understand how to do this from my
vimrc if possible.