Sort code code blocks based on case labels

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

I want to convert -

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

at -

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");
}
+4
source share
4 answers
  • Turn each case into one liner:

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

    :fromline,tolinesort
    
  • Reformat them:

    :fromline,tolines/§/\r/g
    

Notes:

  • Visual mode can be a practical way to determine the range for these commands.
  • You can make a macro if you need to do this often.
+4
source

My AdvancedSorters Plugin simplifies the steps described in @romainl's answer:

:/^switch/+2,/default:/-1 SortRangesByHeader /case /

case. :SortRangesByHeader case .

+2

:

:command! -range SortCases execute "<line1>,<line2>!ruby -e 'puts STDIN.read.split(/(?<=\\n)(?=[\\x20\\x09]*(?:case|default)\\b)/).sort'"

then you can do vi{:SortCases<CR>to do what you need to do.

+1
source

I wrote a plugin for this with the following command:

:SortBlockBy case

Check it out https://github.com/chiedo/vim-sort-blocks-by

+1
source

Source: https://habr.com/ru/post/1547872/


All Articles