Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto indent in vim string replacement new line?

Tags:

regex

vim

I'm using the following command to auto replace some code (adding a new code segment after an existing segment)

%s/my_pattern/\0, \r some_other_text_i_want_to_insert/

The problem is that with the \r, some_other_text_i_want_to_insert gets inserted right after the new line:

mycode(
  some_random_text my_pattern
)

would become

mycode(
   some_random_text my_pattern
some_other_text_i_want_to_insert   <--- this line is NOT indented
)

instead of

mycode(
   some_random_text my_pattern
   some_other_text_i_want_to_insert  <--- this line is now indented
)

i.e. the new inserted line is not indented.

Is there any option in vim or trick that I can use to indent the newly inserted line?

Thanks.

like image 223
rxin Avatar asked Apr 28 '10 19:04

rxin


2 Answers

Try this:

:let @x="some_other_text_i_want_to_insert\n"
:g/my_pattern/normal "x]p

Here it is, step by step:

First, place the text you want to insert in a register...

:let @x="some_other_text_i_want_to_insert\n"

(Note the newline at the end of the string -- it's important.)

Next, use the :global command to put the text after each matching line...

:g/my_pattern/normal "x]p

The ]p normal-mode command works just like the regular p command (that is, it puts the contents of a register after the current line), but also adjusts the indentation to match.

More info:

:help ]p
:help :global
:help :normal
like image 154
Bill Odom Avatar answered Sep 20 '22 04:09

Bill Odom


%s/my_pattern/\=submatch(0).", \n".matchstr(getline('.'), '^\s*').'some_other_text'/g

Note that you will have to use submatch and concatenation instead of & and \N. This answer is based on the fact that substitute command puts the cursor on the line where it does the substitution.

like image 39
ZyX Avatar answered Sep 22 '22 04:09

ZyX