Search code examples
sortingvim

How to sort paragraphs according to their headings in Vim?


Let's say we have the following paragraphs that are separated by a blank line from each other:

B Heading
Lorem ipsum 1.
Lorem ipsum 2.

A Heading
Lorem ipsum 3.
Lorem ipsum 4.

How to sort these paragraphs with respect to their headings and obtain the following text?

A Heading
Lorem ipsum 3.
Lorem ipsum 4.

B Heading
Lorem ipsum 1.
Lorem ipsum 2.

Solution

  • One solution is to concatenate your paragraphs before sorting.

    Say that you do not use the @ symbol in your text, you can use:

    :%s/\(.\+\)\n/\1@/
    

    to do that. Then you can sort your lines with

    :sort
    

    and at last proceed to the reverse operation to get your paragraphs back:

    :%s/@/\r/g