Easily reformat function arguments to multiple lines in Vim

In particular, when editing legacy C ++ code, I often manually reformat something like this:

SomeObject doSomething(firstType argumentOne, secondType argumentTwo, thirdType argumentThree); 

more or less like this:

 SomeObject doSomething(firstType argumentOne, secondType argumentTwo, thirdType argumentThree); 

Is there a built-in command for this? If not, can someone suggest a plugin or provide some VimScript code for it? ( J or gq can very easily change the process, so you don't need to go in both directions.)

+8
vim formatting arguments
source share
3 answers

You can use splitjoin .

 SomeObject doSomething(firstType argumentOne, secondType argumentTwo, thirdType argumentThree); 

Inside or in brackets, type gS to separate. You get:

 SomeObject doSomething(firstType argumentOne, secondType argumentTwo, thirdType argumentThree); 

You can also use vim-argwrap

+5
source share

Here is what I put into my .vimrc . It is more flexible than @rbernabe's answer; it formats based on the global settings of cinoptions and simply breaks into commas (and therefore can be used for more functions if necessary).

 function FoldArgumentsOntoMultipleLines() substitute@,\s*@,\r@ge normal v``=" endfunction nnoremap <F2> :call FoldArgumentsOntoMultipleLines()<CR> inoremap <F2> <Esc>:call FoldArgumentsOntoMultipleLines()<CR>a 

This displays F2 in normal and insert mode to perform searches and replace in the current line, which converts all commas (with 0 or more spaces after each) to a comma with a carriage return after each, then selects the whole group and indentation using Vim builtin = .

A well-known drawback of this solution relates to lines that include several parameters of the template (it is divided only by their commas, and not only by commas of normal parameters).

+3
source share

I would set the register to a predefined macro. After some tests, I got the following:

 let @x="/\\w\\+ \\w\\+(\nf(_:s\\(\\w\\+\\)\\@<=,/,\\r /g\n" 

Using this line in your vimrc, you can format the methods by executing the x: @x macro with the cursor over the line you want to format. It adds 12 spaces for indentation, specified as follows:

 | SomeObject doSomething(firstType argumentOne, secondType argumentTwo, thirdType argumentThree); 

After executing the macro: @x you get

 SomeObject doSomething(firstType argumentOne, secondType argumentTwo, thirdType argumentThree); 

If you are in the function definition line, you can simply do the replacement:

 :s\(\w\+\)\@,<=,/,\r /g 

This is easy to put in display:

 nmap <F4> :s/\(\w\+\)\@<=,/,\r /g<CR> 
+2
source share

All Articles