Sort by priority (FoldingText)

Is there a way to automatically sort todos by priority tag and go from? If there is and I need to code a recursive function, would someone kindly point me out where is the documentation ?

Project A.todo
Water plant @p3
Buy pot @p1
Buy plant @p2

Project B.todo
Buy eggs @p1
Bake cake @p3
Buy milk @p2

to

Project A.todo
Buy pot @p1
Buy plant @p2
Water plant @p3

Project B.todo
Buy eggs @p1
Buy milk @p2
Bake cake @p3

?

If you haven’t already found a solution, the following thread might be a useful starting point?

http://support.foldingtext.com/t/sorting-items-with-tags-by-due-date/665

You might have to work with a different tag for priorities, e.g. @p(1) instead of @p1. I just tweaked the suggested script to do something like what you’re looking for (very hackishly, not worth sharing), so it’s definitely possible…