Enclosing in parentheses with Vim

Surround.vim should do the trick. If you want to repeat that with '.', see here.


You can define a simple mapping for that sort'a thing. This ought to do it. While in normal mode type z to surround a word in parenthesis.

:nnoremap <leader>z viw<esc>a)<esc>hbi(<esc>lel

For one word, I've been using:

bcw()<Esc>P

That is, go to the start of the word, cut the word and go into insert mode, type the brackets and then exit insert mode and paste the word back in.

Keep in mind that this will overwrite your yank register.

You can, of course replace bcw with whatever movement and selection types you need, like

5cc{<Enter>}<Esc>P

Here's examples using surround.vim. On vim normal mode, place your cursor over the desired word (sunny in this case) and type:

ysiw

Then type )

So:

initial string:

It is sunny outside.

Final string:

It is (sunny) outside.

Extra space: Use the opening paren, or bracket, like ysiw( to surround with parens and a space between paren and start + end of word)

Easier in Visual mode Enter visual mode by pressing v. Now if you type S(, the word will be surrounded by spaces. However if you use the closing ) instead S) it will not be surrounded by spaces.

This applies to all bracket pair surroundings, <> [] {} (), not merely to (). The behavior of S< is such that it expects a tag enclosure so only S> is able to surround as <>.

More:

Type ysiw followed by } to do the same for curlies

Might as well add some more examples here:

  • type cs(' to [c]hange [s]urroundings from ( to '

  • cs'( to change from ' surroundings to ()

  • ds(. to [d]elete ( [s]urroundings altogether

Even more:

And why not quote the rest of Tpope's page to save us from clicking through to the link?

//begin quote:

It's easiest to explain with examples.

Press cs"' inside

"Hello world!" to change it to

'Hello world!'

--

Now press cs'<q> to change it to

<q>Hello world!</q>

--

To go full circle, press cst" to get

"Hello world!"

--

To remove the delimiters entirely, press ds".

Hello world!

--

Now with the cursor on "Hello", press ysiw] (iw is a text object).

[Hello] world!

Let's make that braces and add some space (use } instead of { for no space): cs]{

{ Hello } world!

--

Now wrap the entire line in parentheses with yssb or yss).

({ Hello } world!)

--

Revert to the original text: ds{ds)

Hello world!

--

Emphasize hello: ysiw<em>

<em>Hello</em> world!

--

Finally, let's try out visual mode. Press a capital V (for linewise visual mode) followed by S<p class="important">.

<p class="important">
  <em>Hello</em> world!
</p>

This plugin is very powerful for HTML and XML editing, a niche which currently seems underfilled in Vim land. (As opposed to HTML/XML inserting, for which many plugins are available). Adding, changing, and removing pairs of tags simultaneously is a breeze.

The . command will work with ds, cs, and yss if you install repeat.vim.