How do I wrap text with a custom HTML tag using vim-surround?
Answer
ysst
Explanation
vim-surround's ysst sequence lets you wrap a text object with an arbitrary HTML or XML tag and prompts you to type the tag name. This is one of the more powerful — and underused — features of the plugin.
How it works
ys— "you surround" — begins the surround operations— the secondsis a Vim text object meaning the current sentence. You can substitute any motion or text object here:ysiwfor inner word,ysipfor inner paragraph,ysstfor sentence,yssfor the full linet— the surround characterttells vim-surround to prompt for an HTML/XML tag name- After pressing
t, type the tag name (with optional attributes) and press<CR>
Example
Given this line (cursor anywhere on it):
Hello, world
Press ysstsection<CR> (surround current line with a <section> tag):
<section>Hello, world</section>
Or with attributes: ysstp class="hero"<CR> wraps with <p class="hero">...</p>.
Tips
- Use
ysiwinstead ofyssto wrap just the inner word under the cursor:ysiwtprompts for a tag and wraps only that word dstdeletes the nearest surrounding HTML tag (and its closing pair)cstprompts for a new tag to replace the nearest surrounding one — great for changing<div>to<section>in a single motion- Works with multi-line selections by entering visual mode first, then pressing
Sfollowed byt