Last Updated: January 26, 2021
·
1.125K
· gnapse

Easier use of the vim-surround plugin

Tim Pope's vim-surround plugin is awesome, and this tip makes it a little easier and more intuitive to use in some situations, inspired by how this feature works in TextMate and Sublime out-of-the-box.

My aim when creating these vim key mappings was to achieve surrounding the selected text in visual mode simply by typing the surround character. The only gotcha is that some of these characters, specially the double quotes ", have a special and very useful meaning in visual mode, do I decided to prepend the <leader> key to the key mappings.

So enough chit-chat, and on to the actual code.

" Surround text currently selected while in visual mode
" (The surrounded text is kept selected after being surround)
vmap <leader>" S"lvi"
vmap <leader>' S'lvi'
vmap <leader>` S`lvi`
vmap <leader>( S)lvi(
vmap <leader>{ S}lvi{
vmap <leader>[ S]lvi[
vmap <leader>< S>lvi<

Include the above lines in your ~/.vimrc file, and remember to install the vim-surround plugin if you haven't already.

Now whenever you're in visual mode and you type any of the valid surrounding characters prepended by the leader key, the selected text is surround and remains selected. The valid characters for these are (, {, {, <, ', ", `. Also, the fact that the selection is kept allows for typing more than one surround character, and it keeps surrounding on and on!