Small Hadron Collider
Small Hadron Collider

Reputation: 809

Vim: Splitting a list onto new lines

Is there a Vim command (I'm guessing a search and replace?) that can change:

listThing(["fish", "monkey", "cat", "penguin"])

into:

listThing([
    "fish",
    "monkey",
    "cat",
    "penguin"
])

It's not just adding a newline and tab after a comma, as the first and last line also need to be separate.

Upvotes: 0

Views: 87

Answers (2)

lurker
lurker

Reputation: 58244

Not knowing what else might be in your file that this could match a simple approach would be:

:1,$s/\("[^ ,]*"\|\])\)/\r    \1/g

Which will get you:

listThing([
    "fish",
    "monkey",
    "cat",
    "penguin"
    ])

EDIT: As I stated above but will re-emphasize: how well this works for you might depend upon other similar constructs in your file. Other options would be using the plugin that Ingo suggested, or writing a separate script in awk, perl, or <insert-favorite-script-language-here>.

Upvotes: 2

Ingo Karkat
Ingo Karkat

Reputation: 172590

For a particular case, a :substitute command proposed by @lurker's answer can be sufficient. Unfortunately, with many programming languages, there can be nesting of structures, and it's difficult to process all of these correctly. Therefore, for a robust, "don't make me think" solution, I think you need a plugin. Though I haven't tried it yet, the argwrap plugin offers this.

Upvotes: 2

Related Questions