vimtricks.wiki Concise Vim tricks, one at a time.

How do I surround a visual selection with delimiters using vim-surround?

Answer

S"

Explanation

The vim-surround plugin provides the S command in visual mode to wrap any selection with a delimiter pair. This is one of the most powerful features of the plugin because it works with all three visual modes — characterwise, linewise, and blockwise — each producing different formatting results.

How it works

  1. Enter visual mode and select the text you want to wrap
  2. Press S followed by the desired delimiter

The plugin wraps the entire selection with the chosen surrounding.

Characterwise visual mode (v)

Select specific text with v, then press S":

" Before (select 'Hello world' with viw or manual selection):
Say Hello world today

" After S" with 'Hello world' selected:
Say "Hello world" today

Linewise visual mode (V)

With linewise selections, S places the surroundings on their own lines with proper indentation. Select a line with V, then press S<div>:

" Before:
<p>Some paragraph text</p>

" After VS<div>:
<div>
  <p>Some paragraph text</p>
</div>

This is incredibly useful for wrapping HTML blocks in container elements.

Blockwise visual mode (<C-v>)

In block visual mode, each line in the block gets individually wrapped. Select a column with <C-v>, then press S":

" Before (select the three words in a block):
foo
bar
baz

" After <C-v>jjS":
"foo"
"bar"
"baz"

Wrapping with tags

Visual S shines with HTML tags. Select multiple lines with V, then press S<section class="main">:

<section class="main">
  <h1>Title</h1>
  <p>Content here</p>
</section>

Tips

  • Use gS in visual mode for linewise behavior even with a characterwise selection — this places surroundings on separate lines
  • V + S is the fastest way to wrap code blocks in HTML container tags
  • Combine with vim-repeat to repeat the last visual surround operation on new selections
  • For wrapping a function call around selected text, use S) then insert the function name: select x + 1, press S), then use i to type the function name before the (

Next

How do I edit multiple lines at once using multiple cursors in Vim?