Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort case code blocks on the basis of case labels

Tags:

vim

How does one sort code blocks associated with each case (as part of a large switch case construct) on the basis of the case label?

What I want is to transform -

switch(val)
{
    case C_LABEL:
        /* do something */
        break;

    case A_LABEL:
        /* do something else*/
        break;

    case B_LABEL:
        /* do something really different */
        break;

    default:
        printf("'val' not recognized");
}

into -

switch(val)
{
    case A_LABEL:
        /* do something else */
        break;

    case B_LABEL:
        /* do something really different */
        break;

    case C_LABEL:
        /* do something */
        break;

    default:
        printf("'val' not recognized");
}
like image 979
work.bin Avatar asked Feb 13 '23 13:02

work.bin


1 Answers

  1. Turn each case into a one liner:

    :fromline,tolineg/case/.,/break/s/\n/§
    
  2. Sort them:

    :fromline,tolinesort
    
  3. Reformat them:

    :fromline,tolines/§/\r/g
    

Notes:

  • Visual mode can be a practical way to define the range for those commands.
  • You could make a macro if you have to do that often.
like image 51
romainl Avatar answered Mar 06 '23 10:03

romainl