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

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 operation
  • s — the second s is a Vim text object meaning the current sentence. You can substitute any motion or text object here: ysiw for inner word, ysip for inner paragraph, ysst for sentence, yss for the full line
  • t — the surround character t tells 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 ysiw instead of yss to wrap just the inner word under the cursor: ysiwt prompts for a tag and wraps only that word
  • dst deletes the nearest surrounding HTML tag (and its closing pair)
  • cst prompts 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 S followed by t

Next

How do I copy files to a target directory using netrw's marking system?