Tying it together with an advanced workflow
Let’s say I have a file with 100 functions in it, all randomly ordered. I want to sort these functions lexicographically by their name. We can achieve this with the global command!
It looks complicated. I’ll put the commands here, but an explanation is to follow.
:'<,'>g/^func/,/^}$/s/$\n/%%%
:'<,'>sort
:'<,'>s/%%%/\r/g
That’s basically saying:
- find all lines in the visual range that start with
func, and select from that line down to a line that contains only a closing squiggle brace - in each of those ranges, replace all newlines with
%%% - sort the visual range, achieving the effect of sorting by function name lexicographically
- convert the
%%%delimiters back to newlines
Of course, this is quite a specialised workflow. However, if you have a massive test file that has a bunch of boilerplate-y function definitions, sometimes it’s nice to keep them sorted in lexicographical order.
Try using this trick to sort the function definitions in the editor.