Sort case code blocks on the basis of case labels

vim

Solution

Turn each case into a one liner:

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

Sort them:

:fromline,tolinesort

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.

Problem

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"); } ```

Original source