You could try these 3 commands:
g/^\\begin/,/^\\end/-s/$/\="\<c-a>"/|?^\\begin?,+j!
g/^/m0
%s/\%u0001/\r/g
The first one appends a literal C-a
character at the end of every line in your paragraphs, and joins all the lines in each paragraph.
Now that your paragraphs have been reduced to single lines, the second command can reverse their order.
Finally, the third command splits the lines back into paragraphs, by removing the literal C-a
characters, and replacing them with newlines.
The first command can be explained like this:
g/^\\begin/,/^\\end/-s/$/\="\<c-a>"/|?^\\begin?,+j!
└────────┤ └─────────────────────┤ └────────────┤
│ │ └ and this one (B)
│ └ execute this command (A)
└ for every line beginning with `\begin`
(A)
can be broken down further:
,/^\\end/-s/$/\="\<c-a>"/
│└──────┤│└─┤ └────────┤
│ ││ │ └ with a literal `C-a`
│ ││ │
│ ││ └ replaces any end-of-line
│ ││
│ │└ … and move up one line
│ │
│ └ down to the next line beginning with `\end` …
│
└ from the current line (because there's nothing before the comma; you could write a dot; here it's implicit)
This is a substitution command whose:
- range is
,/^\\end/-
- pattern is
$
- replacement is
\<c-a>
It replaces any end-of-line with a literal C-a
.
(B)
can be broken down like this:
?^\\begin?,+j!
└────────┤ │││
│ ││└ without adding/removing any space
│ ││
│ │└ join all the lines inside the range
│ │
│ └ down to the line below the current line (`+` = `.+1`)
│
└ from the previous line beginning with `\begin`
The 2nd command can be explained like this:
g/^/m0
└─┤ └┤
│ └ move it at the top
│
└ for every line in the file
The 3rd command can be explained like this:
%s/\%u0001/\r/g
└┤ └─────┤ └┤ │
│ │ │ └ globally (i.e. all the occurrences on a line; not just the 1st)
│ │ │
│ │ └ with a newline
│ │
│ └ replace a `C-a` (`0001` is its unicode)
│
└ for every line in the file
For more information, see:
:help :g
:help :s
:help :m
:help :j
Alternatively, I haven't used any of them, but you could try the AdvancedSorters plugin (the ingo-library being a dependency), or this snippet of code.