Reputation: 13
I'm trying to write a crude code formatter in VIM using regex and it's generally going okay but I'm stuck on this one problem: How do I reformat a list only, and if only it's inside of certain type of brackets. Say for example I want to reformat
a = [1, 2, 3, 4]
into
a =
[1,
2,
3,
4]
but not do the operation on
b = |1, 2, 3, 4|
?
so far, I've used this which finds all occurrences of a word + a comma + any character and replaces it with a comma and a return.
au BufWrite <buffer> %s/\w\zs,\ze./,\r/ge
Upvotes: 1
Views: 58
Reputation: 378
You also can use the regex:
:%s/^.*|\n\zs\|,/,\r/g
Which mean ^.*|\n
that match every line that contains the character |
, then the command \zs
surpass this selection, now can match every comma from remaining lines...
Another more general way is:
:%s/^\(\(.*\[.*\)\@!.\)*$\n\zs\|,/,\r/g
which ^\(\(.*\[.*\)\@!.\)*$\n
mean to match every lines that not contains [
.
Upvotes: 0
Reputation: 59297
You could use a mix of :s
and substitute()
to work on the match. Considering the following text, for example:
a = [1, 2, 3, 4]
b = |1, 2, 3, 4|
Using:
:%s/\s*\[.\{-}]/\=substitute(submatch(0), '\s\+', '\n', 'g')
Returns:
a =
[1,
2,
3,
4]
b = |1, 2, 3, 4|
What it does is to match the [...]
and then replace every space inside it with a newline.
Upvotes: 1