Mickey has a nice solution to the last VimGolf in Emacs challenge. It certainly doesn’t win on total keystrokes but it does demonstrate a really powerful method for solving problems like the challenge. Mickey uses sort-regexp-fields
to sort parts of each line by
- Picking out the part of each line after the
=␠
as a field - Sorting the specified fields using the whole field as the key
Since only the specified fields are moved, this effectively switches the ends of the two lines leaving the beginnings of the lines where they were. A very nice solution and a powerful technique. Mickey has an excellent write up on sort-regexp-fields
here.
This result is reminiscent of Fuco’s solution where he specified a rectangle that contained the same fields and then reversed the lines in that rectangle. That got me thinking about whether you could sort those fields instead of reversing them. Fuco used 【Meta+Shift+r】 to reverse the lines so I thought maybe there was a similar command for sorting them—【Meta+Shift+s】 perhaps. It turns out that no such command exists but there is 【Meta+|】 which pipes the rectangle to a shell command and with a preceding 【Ctrl+u】 will replace the rectangle with the result. Thus given
abc 789 def 123 ghi 456
we can get
abc 123 def 456 ghi 789
with
【Ctrl+s Space】 | Move to upper left of triangle |
【Ctrl+Return】 | Enter CUA rectangle mode |
【Ctrl+s 6】 | Move to lower right of triangle |
【Ctrl+u Meta+|】 sort |
Sort and replace rectangle |
That’s a bit faster and easier than sort-regexp-fields
but not as powerful because with sort-regexp-fields
you can use just a part of the field (rather than the whole field) as a key and the fields don’t have to form a rectangle.
To illustrate that last point, suppose you have
abc 789 123 def ghi 456
and you want
abc 123 456 def ghi 789
You can do that with
【Ctrl+x h】 | Mark buffer |
【Meta+x】 sort-regexp-fields |
Call sort-regexp-fields |
[1-9]+ |
Define fields |
\& |
Define keys |
Mickey remarks that these challenges are pointless but fun. They’re certainly fun and they’re pointless in the sense that the solutions are mostly ad hoc and not useful outside of the challenge they solve but I, at least, find them useful as a way to learn new Emacs techniques. With just this last challenge, I learned about reversing lines in a rectangle and sort-regexp-fields
and both of those are things I will most certainly find useful later even if I’m unlikely to need to resolve the particular challenge where I learned them.