Alex
Alex

Reputation: 10136

Insert a number of spaces in replacement

I have a long line of code that I need to split into separate lines:

Method(new Namespace::ClassName(LongParameterName1, LongParameterName1, LongParameterName3));

I want to split it the following way:

Method(new Namespace::ClassName(LongParameterName1,
                                LongParameterName1,
                                LongParameterName3));

The regular expression will be like this:

s:, :,\r                         :

How can I set a number of spaces that are used (if I can)?

NOTE: I have quite a big number of lines like this so that's why I want to use the regex.

Upvotes: 1

Views: 86

Answers (3)

Conner
Conner

Reputation: 31110

I would use the regex first and then indent. For instance...

s:, :,\r:g
V?Method<cr><cr>8>

In real practice I'd probably use >....... instead of 8> because it lets you visualize how much you're indenting.

Upvotes: 1

bPizzi
bPizzi

Reputation: 1025

That how I would do it:

  • set a macro (qa') that search for the next ',' (<escape>\,), hop into edit mode and hit enter (i<enter>), quit recording the macro (q)
  • replay that macro very quickly until I'm done with the line (@a then @@)
  • replace the cursor on the second line and start recording a new macro (qa'): I then press <space> until your parameter is sufficiently tabbed, and move to next line while replacing the cursor on the first caracter (<escape>j^), quit recording the macro (q)
  • and replay that final macro like the first one (@a then @@)

That looks less elegant than regexes, but IMHO, when it's time to get things done, well, it's time to get things done :)

Upvotes: 1

Birei
Birei

Reputation: 36282

You can calculate the position where you want to begin variable names in following lines and use a substitution command with expression, like:

:let c = strridx(getline('.'), '(')
:s/\v(,)/\=submatch(1) . "\r" . printf("%" . c . "s", " ")/g

I wrote them in two instructions to avoid a Markdown scroll, but you can join them with a pipe character.

First instruction searches the position of the last opening parentheses (the first one beginning from the end). And second instruction uses a printf() to insert that number of spaces after the newline character.

It yields:

Method(new Namespace::ClassName(LongParameterName1,
                                LongParameterName1,
                                LongParameterName3));

To repeat this task multiple times you can wrap these instructions in a function and call them from a :g command. I hope you get the idea.

Upvotes: 2

Related Questions