Particularly when editing legacy C++ code, I often find myself manually reformatting something like this:
SomeObject doSomething(firstType argumentOne, secondType argumentTwo, thirdType argumentThree);
to something like this:
SomeObject doSomething(firstType argumentOne,
secondType argumentTwo,
thirdType argumentThree);
Is there a builtin command to do this? If not, can someone suggest a plugin or provide some VimScript code for it? (J
or gq
can reverse the process very easily, so it need not go both ways.)
You can use splitjoin.
SomeObject doSomething(firstType argumentOne, secondType argumentTwo, thirdType argumentThree);
Inside or on brackets, type gS
to split. You get:
SomeObject doSomething(firstType argumentOne,
secondType argumentTwo,
thirdType argumentThree);
You can also use vim-argwrap
Here's what I've put in my .vimrc
. It is more flexible than @rbernabe's answer; it does the formatting based on the cinoptions
global settings and simply breaks on commas (and so can be used on more than functions, if needed).
function FoldArgumentsOntoMultipleLines()
substitute@,\s*@,\r@ge
normal v``="
endfunction
nnoremap <F2> :call FoldArgumentsOntoMultipleLines()<CR>
inoremap <F2> <Esc>:call FoldArgumentsOntoMultipleLines()<CR>a
This maps F2 in normal and insert mode to doing a search and replace on the current line which converts all commas (with 0 or more spaces after each) into commas with a carriage return after each, then selects the whole group and indents it using the Vim builtin =
.
A known shortcoming of this solution is for lines that include multiple template parameters (it breaks on their commas as well instead of just the commas of the normal parameters).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With