c++clang-format

Need help in aligning consecutive assignment little differently


I use clang-format option AlignConsecutiveAssignments: true for C++. However, for the cases like the one below, I would like to avoid extra spacing.

Current output:

int i                                 = 0;
int vol                               = 0;
int mass                              = 0;
string center_of_mass                 = "";
unsigned center_of_gravity            = 0;
int j                                 = 0;
int wt                                = 0;
int longest_variable_name_of_them_all = 0;
// int a           = 0;
cout << "item1       = " << wt << endl;
cout << "longer_item = " << vol << endl;

Desired piecewise alignment result:

int i    = 0;
int vol  = 0;
int mass = 0;
string center_of_mass = "";
unsigned center_of_gravity = 0;
int j  = 0;
int wt = 0;
int longest_variable_name_of_them_all = 0;
// int a           = 0;
cout << "item1       = " << wt << endl;
cout << "longer_item = " << vol << endl;

As a rule of thumb I want to avoid having more than 4 spaces before = (and that's why center_of_mass misaligns with the next line).

Does anyone have a script I can run on the formatted output file? Comments are to be ignored to preserve ASCII art (if any) in them.


Solution

  • What is desired is impossible in clang-format. You can achive it partially by disabling clang-format in code regions like below

    int i    = 0;
    int vol  = 0;
    int mass = 0;
    // clang-format off
    string center_of_mass = "";
    unsigned center_of_gravity = 0;
    // clang-format on
    int j  = 0;
    int wt = 0;
    // clang-format off
    int longest_variable_name_of_them_all = 0;
    // clang-format on
    // int a           = 0;
    cout << "item1       = " << wt << endl;
    cout << "longer_item = " << vol << endl;
    

    Or you can break declarations with empty lines and join long names in code blocks bounced by empty lines.

    int i    = 0;
    int vol  = 0;
    int mass = 0;
    int j    = 0;
    int wt   = 0;
    
    string center_of_mass      = "";
    unsigned center_of_gravity = 0;
    
    int longest_variable_name_of_them_all = 0;
    
    // int a           = 0;
    cout << "item1       = " << wt << endl;
    cout << "longer_item = " << vol << endl;