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/%%% (collapse each function onto one line)
:'<,'>sort (sort the collapsed lines)
:'<,'>s/%%%/\r/g (bring the newlines back)
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 the newline at the end of every line with %%%, squashing the whole function onto one line
- sort the collapsed lines, achieving the effect of sorting the functions lexicographically by name
- convert the %%% delimiters back to newlines
Pressing : while a visual selection is active makes Vim fill in the '<,'> range for you, so for the first two commands you only type what comes after it.
One catch: the collapse shrinks the buffer, which leaves the old '< and '> marks pointing past the end of it — so re-select the collapsed lines before sorting. The sort keeps the line count intact, which is why the final expansion can reuse '<,'> as-is.
Of course, this is quite a specialized 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.
Work through the checklist below to sort the function definitions in the editor.