How do I wrap a word or text object with quotes, brackets, or tags in Vim?
Answer
ysiw)
Explanation
The vim-surround plugin provides the ys (you surround) operator to wrap any Vim text object or motion with a delimiter pair. Combined with Vim's powerful text objects, this lets you add surroundings with surgical precision.
How it works
ystriggers the surround operator- The next part is any motion or text object (e.g.,
iw,iW,it,ap,f,) - The final character is the delimiter to wrap with
So ysiw) means: surround the inner word with parentheses.
Example
Given the text with the cursor on name:
return name;
Pressing ysiw) results in:
return (name);
Common combinations
ysiw" " wrap word in double quotes
ysiw' " wrap word in single quotes
ysiw) " wrap word in parentheses (no space)
ysiw( " wrap word in parentheses (with space)
ysiw] " wrap word in square brackets
ysiw} " wrap word in curly braces
ysiw<em> " wrap word in <em> tag
yss) " wrap entire line in parentheses
ysi") " wrap everything inside quotes with parens
Wrapping with tags
You can wrap text in HTML or XML tags by specifying the full tag:
" With cursor on Hello:
" ysiw<span class="bold"> gives:
<span class="bold">Hello</span>
Visual mode alternative
Select text in visual mode, then press S followed by the delimiter:
viw " select inner word
S" " wrap selection in double quotes
For linewise visual mode (V), the surroundings are placed on separate lines with proper indentation.
Tips
- Use
yssto surround the entire current line, ignoring leading whitespace - Opening brackets
(,{,[add inner spaces; closing brackets),},]do not - Combine with any motion:
ysf,)surrounds from cursor to the next comma with parentheses - Install vim-repeat to make
yscommands repeatable with.