Mert Nuhoglu
Mert Nuhoglu

Reputation: 10143

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.

Upvotes: 12

Views: 1510

Answers (2)

Qeole
Qeole

Reputation: 9174

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

Upvotes: 17

Ingo Karkat
Ingo Karkat

Reputation: 172688

I've written the AdvancedSorters plugin to simplify the three steps given by @Qeole's answer into a single command:

:SortRangesByHeader /\u Heading/

Upvotes: 0

Related Questions