Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easily reformatting function arguments onto multiple lines in Vim

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.)

like image 759
Keith Pinson Avatar asked Oct 04 '12 18:10

Keith Pinson


2 Answers

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

like image 155
Chun Yang Avatar answered Oct 25 '22 17:10

Chun Yang


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).

like image 37
Keith Pinson Avatar answered Oct 25 '22 19:10

Keith Pinson