Two ways of doing this sort of thing are:
With a :substitute
command
:%s/\(foo\)/\r \1/g
This will add a newline and four spaces of "indent" before every matched foo
The \(
and \)
around the search expression /foo/
capture the match into a group, and then the \1
uses the captured group in the replacement. This obviously isn't necessary for simple values of /foo/
.
With a :global
command
You can also do this with the :normal
and :global
commands. For example the following command will indent all lines that match the regexp /foo/
and add a line above them:
:g/foo/normal >>O
This works similar to a :substitute
command, but instead of making a substitution, it applies the normal mode operationoperations indent (>>
) followed by add a line above (O
) to each matching line.
You can adjust the normal mode commands to perform different operations as necessary.
For more details:
:help :global
:help :normal
Using :s
and :g
to Unminify CSS
I'm a little unclear on precisely what you're trying to achieve, but if the goal is to e.g. turn this:
margin:0;padding:0;font-family:verdana;
into this:
margin:0;
padding:0;
font-family:verdana;
^^^^ <- one level of indent
I'd do so with the following two commands:
:%s/;/;\r/g
:g/;/normal >>
If, for some reason, you need to add a specific number of spaces that doesn't match your shiftwidth settings, you could instead do:
:%s/;/;\r/g
:g/;/normal i
^^^^ <- type four spaces after the `i`
Macros
In practice, for the specific case mentioned above, I'd probably have used a recursive macro:
qqq
: Clear out theq
register. Necessary for recursive macros,qq
: Start recording in theq
register,/;[^$]<cr>
: Find the first semi-colon not followed by a newline,:left<cr>
: Remove any existing indentation (to remove automatic indentation),>>
: Add one level of indent,na<cr><esc>
: Jump back to the semi-colon,@q
: Recurse,q
: Finish recording,@q
: Run the macro.
You could also record a macro that runs on a single line and then apply it to every line with the global command.
qqqqq:left<cr>>>f;a<cr><esc>@qq@q
:g/;/norm @q
The macro versions look complicated written down, but because they just use normal editing commands recording them comes naturally (with a bit of practice) and using them is a lot faster than it looks.