Step 10 of 10

19. The Global Command

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.

  1. Select every function with ggVG Start by selecting all of the function definitions — press ggVG.
  2. Collapse each function with :'<,'>g/^func/,/^}$/s/$\n/%%% With the selection active, press : and type g/^func/,/^}$/s/$\n/%%%, then hit Enter.
  3. Re-select the collapsed lines with ggVG The old marks went stale in the collapse — press ggVG for a fresh selection.
  4. Sort them with :'<,'>sort With the selection active, press : and type sort, then hit Enter — the functions will sort by name.
  5. Expand them back with :'<,'>s/%%%/\r/g From normal mode, type :'<,'>s/%%%/\r/g and hit Enter — the newlines will come back.
Select every function with ggVG Start by selecting all of the function definitions — press ggVG.

Next: Collapse each function with :'<,'>g/^func/,/^}$/s/$\n/%%%

Loading editor…