Search code examples
vimneovim

VIM - how to add 2 characters at begining and end of a group of words


I want surround a certain number of words with ** with a single command, without using substitution (%s...).

For example, I'd like foo bar baz to turn into **foo bar baz** with a single command. I want to replace only the occurrence where the cursor is placed.

I know of the plug-in "surround" (testing it right now) but I want to make sure there's no native way to do this.

I can also do it with the following :

:%s/foo bar baz/**%**

But I want to know if the following can be done quickly with one command :

  1. place the cursor at the beginning of the first word
  2. insert **
  3. go to end of third word
  4. insert **

Thanks


Solution

  • First off, this won't work:

    :%s/foo bar baz/**%**
    

    Because % is just a literal %, here. You can reuse the whole match with :help s/\& or :help s/\0:

    :%s/foo bar baz/**&**
    :%s/foo bar baz/**\0**
    

    And because it could perform the replacement in other places, which is not what you want.

    The canonical way to surround some arbitrary text with other text is to:

    1. change the text,
    2. insert the first half of the surrounding text,
    3. insert the original text,
    4. insert the second half of the surrounding text,
    5. leave insert mode.

    In a case like this, where there is no built-in motion that covers exactly the text you want to surround, it would look like this:

    v{motion}c**<C-r>"**<Esc>
    

    where you first select foo bar baz, and then surround it.

    In other cases, when there is a fitting motion, visual selection is unnecessary:

    c{motion}**<C-r>"**<Esc>
    

    See :help c, :help i_ctrl-r, and :help registers.

    If you are curious, I've put together a list of native ways to do what Surround does. "Surround with text" is doable without Surround, but the complexity and fragility grows rapidly, even without getting into more complex scenarios.

    Seriously, just use Surround.