Richard Jarram
Richard Jarram

Reputation: 1004

How to execute specific regex substitution on selected lines in visual mode in vim

I want to replicate the VS code feature of 'highlight and comment out code' (usually bound to keys SHIFT + /) in vim.

I can run :g//s/^/\/\/ / in normal mode to prepend // at the start of every line. I just want to put a constraint on this so it only applies the substitution to lines highlighted in visual mode.

Upvotes: 0

Views: 341

Answers (2)

romainl
romainl

Reputation: 196466

I can run :g//s/^/\/\/ / in normal mode to prepend // at the start of every line.

Well, that would be an unnecessarily complicated way to do it and your command wouldn't really work anyway.

  • :g// either matches nothing or it matches the previous search. What you want, here, is probably something like :g/^/ or :g/$/.

  • A simple substitution on the whole buffer would be much simpler and much faster:

    :%s/^/\/\/ /
    

    Using :help :global in this context provides no value (you want to operate on every line anyway) and is considerably slower (we are talking thousands of times slower)

  • You can use alternative separators to avoid all that backslashing:

    :%s@^@// @
    
  • The last separator is not even needed:

    :%s@^@// <-- there is a space, here
    
  • And the kicker: you can enter command-line mode from visual mode like you would do from normal mode, by pressing :. So you can simply make your visual selection, press :, and run your substitution:

    v                    " enter visual mode
    <motion>             " expand the selection
    :                    " press :
    :'<,'>               " Vim inserts the range covering the visual selection for you
    :'<,'>s@^@// <CR>    " perform your substitution
    

Upvotes: 0

philiptomk
philiptomk

Reputation: 763

Visually select all the lines (using V), then hit :. This will give you :'<,'> which is the range of your visual selection. Then you can add your vim command to it.

I would recommend the following method if you wish to not use plugins.

:'<,'>normal I//

Which is not a substitution. If you want a really nice vim plugin that does this task in a vim manner, check out tpope's vim-commentary which is an essential in my opinion.

Upvotes: 2

Related Questions