How do I wrap text with an HTML tag using vim-surround?
Answer
ysiw<em>
Explanation
The vim-surround plugin makes wrapping text in HTML or XML tags effortless. The ys operator ("you surround") combined with any motion or text object and an HTML tag lets you instantly wrap content without manually typing opening and closing tags.
How it works
ysinitiates the surround operatoriwis the text object (inner word in this case)<em>is the tag to wrap with — surround automatically creates both the opening<em>and closing</em>
Example
With the cursor on the word world:
Hello world today
Pressing ysiw<em> results in:
Hello <em>world</em> today
Wrapping with attributes
You can include HTML attributes in the tag. Pressing ysiw<div class="highlight"> on the word code:
Some code here
Results in:
Some <div class="highlight">code</div> here
Wrapping entire lines
Use yss to surround the entire line. Pressing yss<p> on:
This is a paragraph.
Results in:
<p>This is a paragraph.</p>
Linewise wrapping with Visual mode
Select lines with V, then press S<div> to wrap with proper indentation:
<div>
selected content here
</div>
Tips
- Use any motion with
ys:ys$<span>wraps from cursor to end of line ySS<div>wraps the line and places the tag on separate lines with indentation- Combine with
ysiWto include surrounding whitespace in the selection - Works beautifully with
vim-repeatfor applying the same tag wrap with.