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

How do I change one type of surrounding delimiter to another with vim-surround?

Answer

cs{from}{to}

Explanation

The cs command from the vim-surround plugin lets you swap one type of surrounding delimiter for another in a single motion. It reads two characters: the delimiter to find and the one to replace it with. This eliminates the tedious delete-then-retype workflow when refactoring code.

How it works

  • c means change, s means surrounding
  • The first character is the delimiter to remove (what currently wraps the text)
  • The second character is the delimiter to insert (the new wrapper)
  • For closing delimiters like ), ], }, the replacement has no spaces inside
  • For opening delimiters like (, [, {, the replacement adds spaces inside
  • Use t as the {to} to wrap with an HTML/XML tag (you'll be prompted to type the tag name)

Example

Given the cursor anywhere inside "hello":

print("hello")
  • cs"'print('hello') — double to single quotes
  • cs'(print( hello ) — single quotes to parentheses with spaces
  • cs')print(hello) — single quotes to parentheses without spaces
  • cs(<q>print(<q>hello</q>) — parentheses to an HTML tag
  • cst"print("hello") — HTML tag back to double quotes

Tips

  • Works with any of Vim's built-in surrounding pairs: (, ), [, ], {, }, <, >, ", ', `
  • Use ds{char} to delete surroundings entirely without a replacement
  • Use ys{motion}{char} to add new surroundings to text that doesn't have any
  • Available as tpope/vim-surround (Vim) or kylechui/nvim-surround (Neovim)

Next

How do I configure Vim's command-line tab completion to show all matches and complete to the longest common prefix?