It is possible to do this in one expression if we use a "sub-replace-expression." See bottom for info on that.
The problem here is that you want to do two different things.
Operate on the match as a whole (i.e. surround it with
Operate on each item in the match (i.e. surround them with
You can easily do either one:
but as far as I know there's no way to do both in a single operation. I did try to get the proper output with something like:
But of course the problem with this is that the
\2 matches only the last match from the second set of memory parentheses
\(\) and doesn't "remember" anything before that. So you end up with only the last line.
I would recommend doing some pre/post processing with an additional
:s/// command to get rid of the newlines before/after the fact. Here's what I came up with
1st line (Remove newlines)
.,/\n^$/ This is a range modifier for the search and replace. Without this, the command will go on to mutilate your entire file. Currently it goes from the current line
., to the next blank line
\n^$. I'm not sure how you were intending to split things up, but you need some way to tell it to stop.
s/ The beginning of a search and replace command
\(.*\)\n Match the whole line, but only save the part without the newline.
'\1', Replace line with the match surrounded by single quotes and append a comma.
2nd line (Surround in brackets)
\(.*\), Match the whole line but not the last comma and space
[\1] Surround with brackets and also remove superfluous ending comma and space.
I'm going to keep looking into this, but at the moment I don't think it's possible with a single expression. :(
I have found a way to do this with one expression! Internally this is actually two substitutions, but it is technically one expression. Here's what I came up with:
:s/\v((.+\n)*.+)\n/\= "['" . substitute(submatch(1), '\n', "', '", 'g') . "']" /
:s///: Do a substitution
\v((.+\n)*.+)\n: Basically gathers up all the next non-blank lines and stores it all except for the final
\= Allows us to use an expression in the replacement (see
substitute(submatch(1)...): Replaces all stored
"['" . ... . "']": Prepends
[' and appends
This will start at the position of the cursor and go until it finds a blank line (
^\n). Not grabbing the last
\n is important as without that bit we're left with an additional
', that we don't want at the end.
Some might consider this more complex than the previous two-expression answer. But I thought I would go ahead and add this since it is in fact possible to do it with one expression. :)