tags:

views:

104

answers:

3

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 make the newly inserted line indented?

Thanks.

A: 

Kind of a round-about way of achieving the same thing: You could record a macro which finds the next occurance of my_pattern and inserts after it a newline and your replacement string. If auto-indent is turned on, the indent level will be maintained reagardless of where the occurance of my_pattern is found.

Something like this key sequence:

q 1                  # begin recording
/my_pattern/e        # find my_pattern, set cursor to end of match
a                    # append
\nsome_other_text... # the text to append
<esc>                # exit insert mode
q                    # stop recording

Repeated by pressing @1

meagar
Thanks. My some_other_text_i_want_to_insert actually contains a sub pattern (variable name) in my_pattern. Anyway I can rewrite this?
rxin
A: 
%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.

ZyX
+2  A: 

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
Bill Odom