Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort two-line blocks in Vim?

Tags:

vim

I have a file with the following content:

/** doxygen comment for enum member1 */
COMMON_PREFIX_name1 = 1,
/** doxygen comment for enum member2 */
COMMON_PREFIX_name2 = 2,
/** doxygen comment for enum member3 */
COMMON_PREFIX_name3 = 3,
/** doxygen comment for enum member4 */
COMMON_PREFIX_name4 = 4,
...

Is is possible to sort the definitions by the name1, name2, etc. suffixes in the member names, and keep each comment above the corresponding definition?

like image 851
eckes Avatar asked Aug 03 '11 10:08

eckes


People also ask

How do I sort lines in Vim?

Sorting text in Vim is easy! Select the text, then press : , type sort , then hit enter! It'll sort the whole document by default, but you can enter a range too.


1 Answers

I propose the following sequence of actions.

  1. Join the paired lines:

    :g/^\s*COMMON_PREFIX_/-j!
    
  2. Sort the joined lines by the variable names’ suffixes:

    :sort#\*/\s*COMMON_PREFIX_#
    
  3. Split the sorted lines back:

    :g#\*/\zs\ze\s*COMMON_PREFIX_#s//\r/
    

You can run all three commands at once:

:exe'g/^\s*COMMON_PREFIX_/-j!' | sort#\*/\s*COMMON_PREFIX_# | g#\*/\zs\ze\s*COMMON_PREFIX_#s//\r/
like image 174
ib. Avatar answered Oct 16 '22 13:10

ib.