truthling
truthling

Reputation: 134

Surround visually selected texted with x at beginning and y at end

I know I can surround visually selected text with this macro:

qa        " record a macro in buffer a
x         " cut the selected text
i         " enter insert mode
prefix    " type the desired prefix
<esc>     " exit insert mode
p         " paste the cut text
a         " enter insert mode after the pasted text
postfix   " type the desired postfix
<esc>     " exit insert mode
q         " stop recording

I used it to surround a few words with the prefix {{c1:: and postfix :}}. I was then able to repeat the macro with @a.

My question is, how can I permanently map this macro to a command, so that surrounding text in this way will be available to me across sessions? What would I add to .vimrc or surround.vim?

This seems to be more complicated than other related questions in that I want to surround the text with different strings at the beginning and end of the selected text, and also that the selected text will be unique - I am not wanting to surround each instance of a particular string.

Upvotes: 1

Views: 110

Answers (1)

Oleh
Oleh

Reputation: 612

I would create a function and map it to some key (F3 in my example below):

vnoremap <F3> :call Surround("prfx_", "_psfx")<Enter>
function! Surround(prefix, postfix)
    " get the selection
    let selection = @*
    " remove selected text
    normal gv"xx
    " inserting text with prefix and postfix
    execute "normal i" . a:prefix . selection . a:postfix
endfunction

So function Surround accepts two arguments:

  • 1st - prefix (the default is currently set to "prfx_")

  • 2nd - postfix (the default is set to "_psfx")

If you want to be able to enter function arguments each time you press F3 then just remove <Enter> from key mapping:

vnoremap <F3> :call Surround("prfx_", "_psfx")

Upvotes: 2

Related Questions